Skip to main content
 首页 » 编程设计

python之对 Pandas 数据框进行索引查找。为什么这么慢如何加速

2024年12月31日8zhengyun_ustc

<分区>

假设我有一个 pandas 系列,我想将其用作多重映射(每个索引键有多个值):

# intval -> data1 
a = pd.Series(data=-np.arange(100000), 
              index=np.random.randint(0, 50000, 100000)) 

我想(尽可能快地)从 a 中选择所有值 其中 a 的索引与另一个索引 b 匹配。 (就像一个内部连接。或者一个合并,但对于系列)。

  • a 的索引中可能有重复项。
  • b 可能没有重复项,它不一定是 a 索引的子集。为了给 pandas 最好的机会,我们假设 b 也可以作为排序索引对象提供:
     b = pd.Index(np.unique(np.random.randint(30000, 100000, 100000))).sortvalues() 

所以,我们会有这样的东西:

                      target   
   a        b         result 
3  0        3      3  0 
3  1        7      8  3  
4  2        8      ...      
8  3      ... 
9  4 
... 

我也只对获取结果的值感兴趣(不需要索引 [3,8,...])。

如果 a 没有重复,我们会简单地做:

a.reindex(b)  # Cannot reindex a duplicate axis 

因为 & 维护了 a 的副本,我们不能这样做:

d = a[a.index & b.index] 
d = a.loc[a.index & b.index]  # same 
d = a.get(a.index & b.index)  # same 
print d.shape 

所以我认为我们需要做类似的事情:

common = (a.index & b.index).unique() 
a.loc[common] 

...这很麻烦,但也很慢。它不是构建要选择的项目列表,这很慢:

%timeit (a.index & b).unique() 
# 100 loops, best of 3: 3.39 ms per loop 
%timeit (a.index & b).unique().sort_values() 
# 100 loops, best of 3: 4.19 ms per loop 

...所以它看起来真的很慢地检索值:

common = ((a.index & b).unique()).sort_values() 
 
%timeit a.loc[common] 
#10 loops, best of 3: 43.3 ms per loop 
 
%timeit a.get(common) 
#10 loops, best of 3: 42.1 ms per loop 

...大约每秒 20 次操作。不完全是活泼的!为什么这么慢?

肯定有一种快速的方法可以从 pandas 数据框中查找一组值吗?我不想得到一个索引对象——实际上我所要求的只是对排序索引的合并,或者(较慢的)散列 int 查找。无论哪种方式,这都应该是一个非常的快速操作 -- 而不是在我的 3Ghz 机器上每秒 20 次操作。


还有:

分析 a.loc[common] 给出:

ncalls  tottime  percall  cumtime   percall filename:lineno(function) 
# All the time spent here. 
40      1.01     0.02525  1.018     0.02546 ~:0(<method 'get_indexer_non_unique' indexing.py:1443(_has_valid_type) 
... 
# seems to be called a lot. 
1500    0.000582 3.88e-07 0.000832  5.547e-07 ~:0(<isinstance>) 

附言。我之前发布了一个类似的问题,关于为什么 Series.map 这么慢 Why is pandas.series.map so shockingly slow? .原因是懒惰的底层索引。这似乎并没有发生在这里。


更新:

对于相似大小的 a 和常见的 a 是唯一的:

% timeit a.loc[common] 
1000 loops, best of 3: 760 µs per loop 

... 正如@jpp 指出的那样。 Multiindex 可能是罪魁祸首。