Axe*_*xel 17 python dataframe pandas pandas-groupby
这应该是一个简单的,但不知何故,我找不到一个有效的解决方案.
我有一个pandas数据框,如下所示:
index col1 col2 col3 col4 col5
0 a c 1 2 f
1 a c 1 2 f
2 a d 1 2 f
3 b d 1 2 g
4 b e 1 2 g
5 b e 1 2 g
Run Code Online (Sandbox Code Playgroud)
我想按col1和col2分组,得到sum()col3和col4. Col5可以删除,因为无法聚合数据.
以下是输出的外观.我有兴趣在结果数据帧中同时使用col3和col4.这并不重要,如果col1和col2是索引与否的一部分.
index col1 col2 col3 col4
0 a c 2 4
1 a d 1 2
2 b d 1 2
3 b e 2 4
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
df_new = df.groupby(['col1', 'col2'])["col3", "col4"].sum()
Run Code Online (Sandbox Code Playgroud)
然而,这仅返回聚合的结果col4.
我迷失在这里.我发现的每个例子只聚合一列,但问题显然不会发生.
WeN*_*Ben 30
通过使用 apply
df.groupby(['col1', 'col2'])["col3", "col4"].apply(lambda x : x.astype(int).sum())
Out[1257]:
col3 col4
col1 col2
a c 2 4
d 1 2
b d 1 2
e 2 4
Run Code Online (Sandbox Code Playgroud)
如果你想 agg
df.groupby(['col1', 'col2']).agg({'col3':'sum','col4':'sum'})
Run Code Online (Sandbox Code Playgroud)
小智 12
由于GitHub和Stack Overflow上讨论的 pandas FutureWarning: Indexing with multiple key ,我推荐这个解决方案:
df.groupby(['col1', 'col2'])[['col3', 'col4']].sum().reset_index()
Run Code Online (Sandbox Code Playgroud)
输出:
上面的答案对我不起作用。
df_new = df.groupby(['col1', 'col2']).sum()[["col3", "col4"]]
Run Code Online (Sandbox Code Playgroud)
我按单个分组依据和总和列进行分组。
这是为我工作的。
D1.groupby(['col1'])['col2'].sum() << The sum at the end not the middle.
Run Code Online (Sandbox Code Playgroud)
小智 6
另一个通用的解决方案是
df.groupby(['col1','col2']).agg({'col3':'sum','col4':'sum'}).reset_index()
Run Code Online (Sandbox Code Playgroud)
这将为您提供所需的输出。