reset_index() to original column indices after pandas groupby()?

∥☆過路亽.° 提交于 2019-12-21 19:58:18

问题


I generate a grouped dataframe df = df.groupby(['X','Y']).max() which I then want to write (to csv, without indexes). So I need to convert 'X' and 'Y' back to regular columns; I tried using reset_index(), but the order of columns was wrong.

How to restore columns 'X' and 'Y' to their exact original column position?

Is the solution:

df.reset_index(level=0, inplace=True)

and then find a way to change the order of the columns?


(I also found this approach, for multiindex)


回答1:


This solution keeps the columns as-is and doesn't create indexes, after grouping, hence we don't need reset_index() and column reordering at the end:

df.groupby(['X','Y'],as_index=False).max()

(After testing a lot of different methods, the simplest one was the best solution (as always) and the one which eluded me the longest. Thanks to @maxymoo for pointing it out.)



来源:https://stackoverflow.com/questions/35020064/reset-index-to-original-column-indices-after-pandas-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!