首页 > 解决方案 > 有效地将 pandas 系列浮点数与 pandas 系列 numpy 数组进行比较

问题描述

以下是可重现的并返回所需的结果。

import pandas as pd, numpy as np
np.random.seed(3124)

x = 10 + np.random.rand(10)
y = np.split(10 + np.random.rand(100), 10)

x >= y
# array([[False,  True,  True, False, False, False, False,  True, False, True],
#        ...
#        [False,  True,  True,  True, False,  True, False,  True, False, False]])

np.apply_along_axis(np.greater_equal, 0, x , y)
# same results as x >= y.

但是,如果上面的 x 和 y 是从 pandas 数据框中拉出的,我必须将 pandas 系列数组转换为数组列表。对于大型系列来说,这在计算上是非常昂贵的。

我将如何以更有效的方式完成此任务?

df = pd.DataFrame({'x':x,'y':y})

df['x'].values >= df['y'].tolist()
# same results as above.

df['x'] >= df['y']
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

df['x'].values >= df['y'].values
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

编辑

@Divakar 对上述问题给出了正确答案。但是,在我的实际用例中,数组的y长度都不同。

使用y从上面创建y2更接近我的数据。以下是可重现的。

y2 = [np.resize(a, r) for a,r in zip(y,np.random.randint(2, 10, 10))]
# yields something like:
# [array([10.1269906 , 10.34269353, 10.39461373, 10.022271  , 10.69316165, 10.83981557, 10.03328485, 10.56850597]), 
# array([10.99159117, 10.21215159, 10.65208435, 10.22483111, 10.13748229, 10.72621328]), 
# ...
# array([10.61071355, 10.62141997]), 
# array([10.3899659 , 10.66207985, 10.85937807]), 
# array([10.38374303, 10.93140162, 10.88535643, 10.51529231, 10.60723795, 10.60504599, 10.6773523 ]), 
# array([10.02775067, 10.91382588, 10.31222259, 10.44732757, 10.16980452, 10.88914854, 10.22677905])]

以下返回我想要的结果,但对于我的实际数据框的大小是不可行的。我宁愿用 numpy 以矢量化形式进行。

[x[i] >= y2[i] for i in range(len(y2))]
# returns 
# [array([False, False, False, False, False, False, False, False]),
#  array([False,  True, False,  True,  True, False]),
#  ...
#  array([ True,  True]), 
#  array([ True, False, False]),
#  array([False, False, False, False, False, False, False]),
#  array([ True,  True,  True,  True,  True,  True,  True])]

标签: pythonpandasnumpy

解决方案


获取底层数组数据,这样我们就有y了 as2D数组,我们称它为Yxas 1D,称它为X。然后执行比较杠杆broadcasting,像这样 -

Y = np.concatenate(df.y.values).reshape(-1,len(df.y[0]))
X = df.x.values
out = X >= Y

请注意,这会将每个条目df.yx.

如果您打算将 in 中的每个条目与 inx中的每个条目进行比较df.y,请扩展X2D然后比较 : out = X[:,None] >= Y


推荐阅读