Python Pandas-通过选择多个列对组中多个列的两个数组求和
下面是我的数据框的结构。我需要根据id、国家和州进行分组,并分别聚合向量_1和向量_2。请有人建议如何为多个列添加向量Python Pandas-通过选择多个列对组中多个列的两个数组求和,python,pandas,Python,Pandas,下面是我的数据框的结构。我需要根据id、国家和州进行分组,并分别聚合向量_1和向量_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
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
和apply
对每组进行求和
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]
到目前为止你都尝试了什么?我正在尝试使用聚合函数..类似这样的。。但是遇到了麻烦。groupby('Id','Country','State')。agg({Vector_1:sum})尝试
。agg({Vector_1:sum'},axis=1)
接受了答案。感谢您在pyspark中实现相同的逻辑?我尝试了2-3种不同的逻辑,但没有任何帮助。有什么建议吗?@prabuster我不知道在pyspark里怎么做。也许你可以问一个新问题,给pyspark贴上标签。