我正在尝试向 Pandas GroupBy DataFrame 添加一列。新列(E) 是列(C) 上具有相同键(A,B) 的值的总和。该键由数据帧的另外两列(A,B) 组成。
This is my Dataframe
A B C D
0 foo one 1 15
1 bar one 2 10
2 foo two 4 20
3 bar three 4 5
4 foo two 5 6
5 bar two 6 9
6 foo one 7 8
7 foo three 8 15
what I want:
A B C D E
0 foo one 1 15 8
1 bar one 2 10 2
2 foo two 4 20 9
3 bar three 4 5 4
4 foo two 5 6 9
5 bar two 6 9 6
6 foo one 7 8 8
7 foo three 8 15 8
这是我的代码
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
...: 'foo', 'bar', 'foo', 'foo'],
...: 'B' : ['one', 'one', 'two', 'three',
...: 'two', 'two', 'one', 'three'],
...: 'C' : ['1','2','4','4','5','6','7','8'],
...: 'D' : ['15','10','20','5','6','9','8','15']})
我已经尝试过的
df['E'] =df['C'].groupby(df['A,B']).transform('sum')
但不起作用
婷婷同学_
相关分类