如何阻止聚合函数向数据帧添加不需要的行



我写了一行代码,按列对数据帧进行分组

df = df.groupby(['where','when']).agg({'col1': ['max'], 'col2': ['sum']})

使用以上代码后,输出中的聚合列有两个额外的行,其中"max"one_answers"sum"占据了"col1"one_answers"col2"索引下方的一列。它看起来像这样:

最大ab
col1 col2
总和
其中
主页 1 a
工作 2 b

您需要的是reset_index并提前将列名传递给聚合函数。

使用以下操作:

df = df.groupby(['where','when']).agg(col1 = ('col1', 'max'), col2 = ('col2', 'sum')).reset_index()

数据帧:

where  when  col1  col2
0  home     1     1     1
1  work     2     2     2
2  home     1     3     3

输出:

where  when  col1  col2
0  home     1     3     3
1  work     2     2     2

更新:

我们可以将as_index = False传递给groupby,这将阻止panda将密钥作为索引,因此之后我们不需要重置索引。

df = df.groupby(['where','when'], as_index = False).agg(col1 = ('col1', 'max'), col2 = ('col2', 'sum'))

最新更新