After groupby, how to smooth column headers?

I am trying to delete multiple pandas frames in the same Id column, but when I try to merge, I get a warning:

KeyError: 'Id'.

I think this may be due to the fact that my dataframes have offset columns as a result of the groupby , but I could have been mistaken. In any case, I can’t figure out how to β€œunzip” my dataframe column headers. None of the answers to this question seem to work.

My groupby code:

 step1 = pd.DataFrame(step3.groupby(['Id', 'interestingtabsplittest2__grp'])['applications'].sum()) step1.sort('applications', ascending=False).head(3) 

Return:

offset headers

How to get these shifted headers to the top level?

+6
source share
1 answer

You are looking for .reset_index() .

 In [11]: df = pd.DataFrame([[2, 3], [5, 6]], pd.Index([1, 4], name="A"), columns=["B", "C"]) In [12]: df Out[12]: BC A 1 2 3 4 5 6 In [13]: df.reset_index() Out[13]: ABC 0 1 2 3 1 4 5 6 

Note. To avoid this step, use as_index=False when doing groupby.

 step1 = step3.groupby(['Id', 'interestingtabsplittest2__grp'], as_index=False)['applications'].sum() 
+21
source

All Articles