pandas groupby 没有将按列分组转换为索引 [英] pandas groupby without turning grouped by column into index
问题描述
pandas groupby 的默认行为是将 group by 列转换为索引并将它们从数据框的列列表中删除.例如,假设我有一个包含这些列的 dataFrame
The default behavior of pandas groupby is to turn the group by columns into index and remove them from the list of columns of the dataframe. For instance, say I have a dataFrame with these columns
col1|col2|col3|col4
如果我以这种方式应用带有列 col2
和 col3
的 groupby
if I apply a groupby say with columns col2
and col3
this way
df.groupby(['col2','col3']).sum()
数据框 df
在列列表中不再有 ['col2','col3']
.它们会自动转换为结果数据帧的索引.
The dataframe df
no longer has the ['col2','col3']
in the list of columns. They are automatically turned into the indices of the resulting dataframe.
我的问题是如何对列执行 groupby 并将该列保留在数据框中?
My question is how can I perform groupby on a column and yet keep that column in the dataframe?
推荐答案
df.groupby(['col2','col3'], as_index=False).sum()
这篇关于pandas groupby 没有将按列分组转换为索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!