yam*_*oel 1 python dataframe pandas pandas-groupby
我需要添加各列的行值并将其存储在相同(或新)数据框中。例如:数据框看起来像这样:
id col1 col2 col3 col4 ... col50
1 1 12 3 44 0
1 7 0 7 2 10
1 2 3 0 4 9
3 9 0 1 0 0
3 1 1 11 1 0
Run Code Online (Sandbox Code Playgroud)
预期值应该是:
id col1 col2 col3 col4... col50
1 10 15 10 46 19
3 10 1 12 1 0
Run Code Online (Sandbox Code Playgroud)
如果我使用tmp2 = tmp2.iloc[:,1:50].sum(),它会改变数据框的尺寸。
这是按 进行分组聚合id。因此,使用一个GroupBy对象:
res = df.groupby('id', as_index=False).sum()
print(res)
id col1 col2 col3 col4 col50
0 1 10 15 10 50 19
1 3 10 1 12 1 0
Run Code Online (Sandbox Code Playgroud)