python - Pandas - 通过选择多列对组中多列的两个数组求和
问题描述
下面是我的数据框的结构。我需要根据 id、country 和 state 分组并分别聚合vectors_1和vector_2。请有人建议如何为多列添加向量
Id Country State Vector_1 Vector_2
1 US IL [1.0,2.0,3.0,4.0,5.0] [5.0,5.0,5.0,5.0,5.0]
1 US IL [5.0,3.0,3.0,2.0,1.0] [5.0,5.0,5.0,5.0,5.0]
2 US TX [6.0,7.0,8.0,9.0,1.0] [1.0,1.0,1.0,1.0,1.0]
输出应如下所示
Id Country State Vector_1 Vector_2
1 US IL [6.0,5.0,6.0,6.0,6.0] [10.0,10.0,10.0,10.0,10.0]
2 US TX [6.0,7.0,8.0,9.0,1.0] [1.0,1.0,1.0,1.0,1.0]
解决方案
如果您不是Vector_1
,请先尝试转换它们。Vector_2
np.array
cols = ['Vector_1', 'Vector_2']
df[cols] = df[cols].applymap(lambda x: np.array(x))
然后使用groupby
withapply
对每个组求和
result = (df.groupby(['Id', 'Country', 'State'])[cols]
.apply(lambda x: x.sum())
.reset_index())
result
Id Country State Vector_1 Vector_2
0 1 US IL [6.0, 5.0, 6.0, 6.0, 6.0] [10.0, 10.0, 10.0, 10.0, 10.0]
1 2 US TX [6.0, 7.0, 8.0, 9.0, 1.0] [1.0, 1.0, 1.0, 1.0, 1.0]
推荐阅读
- php - Nginx 中的反向代理问题在同一网络上的 2 台服务器之间,一台服务器使用 apache,另一台是 node.js
- python - 你如何对python中的字符串数字列表进行排序?
- c++ - 在 VS Code 中使用 Linux 上的 MinGW 交叉编译适用于 Windows 的 SDL 程序?
- linux - 如何在共享库中嵌入数据?
- discord.js - Discord.js setVoiceChannel
- c - 关于用户名/密码应用程序中逻辑运算符的语义错误
- android - Android 地理围栏 - 仅当 Google 地图在任何应用程序上运行时才有效
- java - 我想加入表格,但这是显示错误消息
- javascript - 反应 setState 没有正确更新
- testing - 如何在测试(颤振)中访问这些字段?