Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 914
bkd Avatar asked Jan 26 '16 17:01

bkd


1 Answers

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.)

like image 178
bkd Avatar answered Nov 14 '22 23:11

bkd