Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - pandas groupby without turning grouped by column into index

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

if I apply a groupby say with columns col2 and col3 this way

df.groupby(['col2','col3']).sum()

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.

My question is how can I perform groupby on a column and yet keep that column in the dataframe?

question from:https://stackoverflow.com/questions/65890743/pandas-unable-to-remove-column-from-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
df.groupby(['col2','col3'], as_index=False).sum()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...