【问题标题】:Efficiently compare pandas series of floats to pandas series of numpy arrays有效地将 pandas 系列浮点数与 pandas 系列 numpy 数组进行比较
【发布时间】:2019-01-08 20:34:42
【问题描述】:

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

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])]

【问题讨论】:

  • 是的,我认为尺寸参差不齐,您必须求助于一些循环的解决方案。在这里看不到矢量化的帮助。
  • 是否有一个矢量化函数可以用np.nan 填充所有数组,使它们的长度都相同,然后使用您的解决方案?
  • @Divakar 您在上面的评论中链接到的问题的答案非常有效。谢谢。

标签: python pandas numpy


【解决方案1】:

获取底层数组数据,这样我们就有y作为2D数组,我们称之为Y和x作为1D,称之为X。然后进行比较以利用broadcasting,就像这样 -

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

请注意,这会将df.y 中的每个条目与x 进行比较。

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

【讨论】:

  • 谢谢@Divakar。您按照我的措辞回答了我的问题,所以我接受了它作为答案。虽然对于我的实际用例,y 中的每个数组都是不同的大小。
  • 类似y2 = [np.resize(a, r) for a,r in zip(y,np.random.randint(2, 10, 10))]
  • @Clay 您可以为这种情况添加示例以及问题中的预期输出吗?
  • @ Divakar - 添加了更多细节。谢谢。
猜你喜欢
  • 2019-12-20
  • 1970-01-01
  • 2020-10-07
  • 2019-01-19
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多