Skip to main content
 首页 » 编程设计

python之值与一组值的矢量化比较

2025年02月15日15三少

我有一个 pd.Dataframe,其中有一列包含一个值,例如

df.iloc[:10]['occ'] 
Out[18]:  
0    4220 
1     205 
2    7630 
3    8965 
4     430 
5    3930 
6    4230 
7    5620 
8    4040 
9    4130 

然后我有另一个数据框,其中包含不同组的 start 和 end 值。我想根据它们的 occ 值将组分配给第一个数据框。

       start   end 
group              
10        10   950 
11      1000  3540 
12      3600  3655 
13      3700  3955 
14      4000  4160 

由于这些组不相交,我们有一个简单的双射。我计划为每个 occ 值取最后一行小于所述 occ 值的组索引。

testAgainst = np.repeat(dfGroups['start'].values[np.newaxis, :], repeats=10, axis=0) 
 
array([[  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000], 
       [  10, 1000, 3600, 3700, 4000, 4200, 4300, 4700, 5000, 6000, 6200, 
        7000, 7700, 9000]]) 

现在,由于维度是 (10,) 和 (10, 14),应该会自动广播。我期待能够做到

df.iloc[:10]['occ'] < testAgainst 

并得到结果

0  False False False False False False True  True  True  True  True  True  True  True  
1  False True  True  True  True  True  True  True  True  True  True  True  True  True  

对于前两行,因为4220大于4200(以及之后的所有数字),205大于10。

但是,我明白了

Traceback (most recent call last): 
  File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
  File "<ipython-input-28-1bce7761846c>", line 1, in <module> 
    df.iloc[:10]['occ'] < testAgainst 
  File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/pandas/core/ops.py", line 832, in wrapper 
    return self._constructor(na_op(self.values, np.asarray(other)), 
  File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/pandas/core/ops.py", line 792, in na_op 
    result = getattr(x, name)(y) 
ValueError: operands could not be broadcast together with shapes (10,) (10,14)  
  1. 为什么广播在这里不起作用?
  2. 鉴于这行不通,将组分配到我的数据框的最有效方法是什么(真实案例:10-15 个组,但 df 中有 2500 万行)。

请您参考如下方法:

1) 广播失败的原因是 Series 对象形成一维标记数组 [shape=(10,)] 与二维数组 [shape=(1, 14)] 进行比较。

让我们考虑一下:ser = df.iloc[:10]['occ']

如果你这样做了:

>>> ser.iloc[0] < testAgainst 
array([[False, False, False, False, False, False,  True,  True,  True, 
     True,  True,  True,  True,  True]], dtype=bool) 

这意味着如果您可以对系列的所有行应用相同的比较,就会得到正确的结果。

>>> ser.apply(lambda x: x < testAgainst.ravel()) 

但是,这确实很慢,因为它没有矢量化,因此将其应用于大量行是不可行的。

您现在可以做的是以在其中插入额外维度的方式 reshape 系列。

这允许 NumPy 分别匹配序列 (10, 1) 和数组 (1, 14) 的两个形状,以便可以通过配对来比较它们各自的维度。

2) 更优的解决方案可能是:

>>> pd.Series((ser.values[:, None] < testAgainst).tolist())   # same as ser.values.reshape(-1,1) 

结果输出:

0    [False, False, False, False, False, False, Tru... 
1    [False, True, True, True, True, True, True, Tr... 
2    [False, False, False, False, False, False, Fal... 
3    [False, False, False, False, False, False, Fal... 
4    [False, True, True, True, True, True, True, Tr... 
5    [False, False, False, False, True, True, True,... 
6    [False, False, False, False, False, False, Tru... 
7    [False, False, False, False, False, False, Fal... 
8    [False, False, False, False, False, True, True... 
9    [False, False, False, False, False, True, True... 
dtype: object 

注意:测试数组的一个样本就足够了,您不需要重复这个数组来匹配系列对象的形状。