【问题标题】:The most efficient way to search every element of a list in a dataframe搜索数据框中列表的每个元素的最有效方法
【发布时间】:2021-01-31 09:48:42
【问题描述】:

我有一个超过 1M 的数据集,例如 d。我需要找到一个数据帧的索引,比如 seekframe,它在该数据集中超过 1500 个元素。

import pandas as pd 

d=pd.DataFrame([225,230,235,240,245,250,255,260,265,270,275,280,285,290,295,300,305,310,315,320])
seekingframe=pd.DataFrame([275,280,285,290,295,300,305,310,315,320,325,330,335,340,345,350,355,180,255,260])

我需要尽快找到 d 中 seekframe 的每个元素。我的意思是,我需要一个像这样的最终数组:

array([ 10, 11,  12, 13, 14, 15, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, 6, 7])

或类似的差异数组

[11, 12, 13, 14, 15, 16, 17, 18]

或某物表示相同或不同。实际上,如果可能的话,我宁愿放弃那些不同的集合。

【问题讨论】:

  • 每个数据帧中的数字是否唯一?
  • 数字是(严格)单调的吗?
  • 这似乎也是一个 numpy 问题,所以如果没问题就标记一下。

标签: python-3.x pandas numpy dataframe data-science


【解决方案1】:

使用 numpy 可能会更快。在这些小的唯一数组上,numpy 比 pandas .isin() 快 100 倍以上,而无需将 assume_unique=True 传递给 numpy 函数,该函数找到两个数组的交集 (np.in1d) 并返回 TrueFalse

如果你确实通过assume_unique=True,速度会快 300 倍:

#finding similar
%timeit d[d[0].isin(seekingframe[0])].index
404 µs ± 6.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

#finding difference
%timeit seekingframe[~seekingframe[0].isin(d[0])].index
458 µs ± 2.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# finding similar with numpy arrays and NOT passing `assume_unique=True`
a = d[0].to_numpy()
b = seekingframe[0].to_numpy()
%timeit np.arange(a.shape[0])[np.in1d(a, b)]

35.4 µs ± 779 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

# finding similar with numpy arrays and passing `assume_unique=True`
a = d[0].to_numpy()
b = seekingframe[0].to_numpy()
%timeit np.arange(a.shape[0])[np.in1d(a, b, assume_unique=True)]

12 µs ± 337 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2022-11-16
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多