【发布时间】:2018-07-19 10:07:53
【问题描述】:
我有一个包含两列的数据框,A 列是整数列表,B 列包含整数。
我想要的输出是一个熊猫系列,它的值是列表,通过将A 中列表中的每个元素乘以B 列中的相应元素来获得。
我尝试使用apply,但出现意外行为。
设置 1:
如果 A 中的列表 碰巧 的最大长度等于 DataFrame 的列数,我会得到一个具有原始形状的 DataFrame,而不是 TimeSeries
ts1 = pd.Series([[1, 2], [3], [4, 5]])
ts2 = pd.Series([1, 2, 3])
df = pd.concat([ts1, ts2], keys=['A', 'B'], axis=1)
def foo(x):
return [el * x['B'] for el in x['A']]
df.apply(foo, axis=1)
A B
0 1 2
1 6 6
2 12 15
设置 2:
对于A(这是我的用例)中列表的任意长度,apply 失败:
ts1 = pd.Series([[1, 2], [3], [4, 5, 6]])
ts2 = pd.Series([1, 2, 3])
df = pd.concat([ts1, ts2], keys=['A', 'B'], axis=1)
def foo(x):
return [el * x['B'] for el in x['A']]
df.apply(foo, axis=1, reduce=False)
ValueError: could not broadcast input array from shape (3) into shape (2)
我将 pandas 0.21.1 与 python 3.4 一起使用
我尝试使用 apply 的 broadcast 和 reduce 参数,但没有成功。
问题:
- 在我的 pandas 版本中是否有有效的 apply 语法来实现这一点?
- 对失败的原因有何见解?
- 还有更好的解决方案/方法,同时使用 numpy 或其他 pandas 函数?我目前的解决方案感觉根本不是最佳的
【问题讨论】:
-
尝试升级 pandas,对我来说
pandas 0.23.1工作正常。