首页 > 解决方案 > 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]

标签: pythonpandas

解决方案


如果您不是Vector_1,请先尝试转换它们。Vector_2np.array

cols = ['Vector_1', 'Vector_2']

df[cols] = df[cols].applymap(lambda x: np.array(x))

然后使用groupbywithapply对每个组求和

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]

推荐阅读