python - 熊猫适用于以列表为值的数据框
问题描述
我有一个包含两列的数据框,列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)
我在 python 3.4 中使用 pandas 0.21.1
我试图玩弄applybroadcast
和reduce
参数,但没有成功。
问题:
- 在我的熊猫版本中是否有有效的 apply 语法来实现这一点?
- 关于它为什么失败的任何见解?
- 任何更好的解决方案/方法,也使用 numpy 或其他熊猫功能?我目前的解决方案根本感觉不是最佳的
解决方案
您还可以将列表转换为 numpy 数组并在两个系列上使用广播
df.A.apply(np.array) * df.B
#Out:
0 [1, 2]
1 [6]
2 [12, 15]
dtype: object
推荐阅读
- javascript - 一个属性值可以作为参数传递给另一个属性,其值是通过函数计算的吗?(在带有类的 Javascript ES6 中)
- r - 如何为我的 3 个图在一张图中拟合一条线性回归线?
- c++ - 为什么没有执行其中一个 while 循环(C++)?
- javascript - nestjs如何不将拦截器全局应用于控制器
- jackson - Jackson YAML Parser 删除了特殊字符
- python - 如何让机器人加入语音频道 discord.py
- java - 让用户在Java的方法参数中手动编写接收器参数有什么意义吗?
- r - R data.table/regex - 在第一次和最后一次出现字符时 tstrsplit
- laravel - 如何比较 2 个集合的所有属性并返回 Laravel 上的不同对象?
- visual-studio - 有没有办法通过 VS2019 在 docker 容器中运行 .net 核心单元测试?