python - Python中来自不同Pandas Dataframe系列的一系列两个列表的元素乘法
问题描述
我有一个数据框,其中有两个系列,每个系列都包含许多列表。我想对“列表 A”中的每个列表与“列表 B”中的相应列表执行逐元素乘法。
df = pd.DataFrame({'ref': ['A', 'B', 'C', 'D'],
'List A': [ [0,1,2], [2,3,4], [3,4,5], [4,5,6] ],
'List B': [ [0,1,2], [2,3,4], [3,4,5], [4,5,6] ] })
df['New'] = df.apply(lambda x: (a*b for a,b in zip(x['List A'], x['List B'])) )
目的是获得以下输出:
print(df['New'])
0 [0, 1, 4]
1 [4, 9, 16]
2 [9, 16, 25]
3 [16, 25, 36]
Name: New, dtype: object
但是我收到以下错误:
KeyError: ('List A', 'occurred at index ref')
解决方案
您的代码几乎就在那里。大多数情况下,您需要通过axis=1
才能申请:
df["new"] = df.apply(lambda x: list(a*b for a,b in zip(x['List A'], x['List B'])), axis=1)
print(df)
输出是:
ref List A List B new
0 A [0, 1, 2] [0, 1, 2] [0, 1, 4]
1 B [2, 3, 4] [2, 3, 4] [4, 9, 16]
2 C [3, 4, 5] [3, 4, 5] [9, 16, 25]
3 D [4, 5, 6] [4, 5, 6] [16, 25, 36]
推荐阅读
- indexoutofboundsexception - javaFx setCellFactory 导致索引超出范围异常奇怪的行为
- list - 在 Tcl 代码中,我可以在 foreach 中迭代列表时附加和排序列表吗
- javascript - 如何打开从 Chrome / Edge 到 IE 的 html 超链接?
- html - 如何始终在 html5 上显示视频播放器控件
- flutter - Flutter PageView 与 BottomNavigationBar 结合使用非常慢
- asp.net-mvc-5 - 通过在asp.net mvc5应用程序中调用外部corejwtapi获取JWT Token
- mysql - 错误 Connect MySQL Communications link failure 成功发送到服务器的最后一个数据包是 0 毫秒前
- c# - C#如何从自定义事件中清除处理程序
- jupyter-notebook - 如何在 Jupyter 笔记本中显示已完成的 Chaco.plot.Plot 对象?
- python - 为什么我的不和谐机器人不会在频道 discord.py 中发送消息