我如何分组 ID 并相互添加列

How can i groupby ID and add columns to each other

     id  volume   location_ 10   location_ 100  location_ 1000  location_ 1002  location_ 1005  
0   14121   19  0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
1   14121   19  0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
2   14121   19  0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
3   14121   19  0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
4   9320    200 0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
5   9320    116 0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
6   9320    200 0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0
7   9320    116 0   0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   0

我有这样的df。我想按 ID 分组,我必须达到类似的目的。 14121中有4个id,它们的体积之和是76,我该怎么做?

   id    0  1  2  3  4  5  6  7 ... vol
0 14121  0  0  0  0  0  0  0  0 ...  76
1 9329   0  0  0  0  0  0  0  0 ... 632
2 14934  0  0  0  0  0  0  0  0 ...   4

我不确定位置列是什么。以下是获取 ID 总和的方法。

import pandas as pd
df = pd.DataFrame({'id':[14121,14121,14121,14121,9320,9320,9320,9320,14934,14934,14934,14934],
                   'volume':[19,19,19,19,200,116,200,116,1,1,1,1]})
print (df)
print (df.groupby('id')['volume'].sum())

输入数据帧:

       id  volume
0   14121      19
1   14121      19
2   14121      19
3   14121      19
4    9320     200
5    9320     116
6    9320     200
7    9320     116
8   14934       1
9   14934       1
10  14934       1
11  14934       1

输出数据帧:

id
9320     632
14121     76
14934      4

或者你也可以给:

print (df.groupby('id').agg(vol_sum = ('volume','sum')).reset_index())

输出将是:

      id  vol_sum
0   9320      632
1  14121       76
2  14934        4