Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder columns in pandas pivot table

Tags:

python

pandas

I have a pandas dataframe created using the pivot_table method. It is structured as follows:

import numpy as np
import pandas 

datadict = {
 ('Imps', '10day avg'): {'All': '17,617,872', 'Crossnet': np.nan, 'N/A': '17,617,872'},
 ('Imps', '30day avg'): {'All': '17,302,111', 'Crossnet': '110','N/A': '18,212,742'},
 ('Imps', '3day avg'): {'All': '8,029,438', 'Crossnet': '116', 'N/A': '8,430,904'},
 ('Imps', 'All'): {'All': '14,156,666', 'Crossnet': '113', 'N/A': '14,644,823'},
 ('Spend', '10day avg'): {'All': '$439', 'Crossnet': np.nan, 'N/A': '$439'},
 ('Spend', '30day avg'): {'All': '$468', 'Crossnet': '$0', 'N/A': '$492'},
 ('Spend', '3day avg'): {'All': '$209', 'Crossnet': '$0', 'N/A': '$219'},
 ('Spend', 'All'): {'All': '$368', 'Crossnet': '$0', 'N/A': '$381'}
}
df = pandas.DataFrame.from_dict(datadict)
df.columns = pandas.MultiIndex.from_tuples(df.columns)

I tried to reorder the nested columns under 'Spend' and 'Imps' in a new order using both of the below methods, however the order remains unchanged despite no errors being thrown:

df['Spend']=df['Spend'].reindex_axis(['3day avg','10day avg','30day avg','All'],axis=1)
df['Spend']=df['Spend'][['3day avg','10day avg','30day avg','All']]
like image 830
ChrisArmstrong Avatar asked Oct 02 '22 09:10

ChrisArmstrong


1 Answers

One way is to create the MultiIndex and reindex by that:

In [11]: mi = pd.MultiIndex.from_product([['Imps', 'Spend'], ['3day avg','10day avg','30day avg','All']])

In [12]: df.reindex_axis(mi, 1)
Out[12]: 
               Imps                                        Spend                          
           3day avg   10day avg   30day avg         All 3day avg 10day avg 30day avg   All
All       8,029,438  17,617,872  17,302,111  14,156,666     $209      $439      $468  $368
Crossnet        116         NaN         110         113       $0       NaN        $0    $0
N/A       8,430,904  17,617,872  18,212,742  14,644,823     $219      $439      $492  $381

Note: MultiIndex.from_product is new in 0.13, if you're using a pandas older than that use pd.MultiIndex.from_tuples(list(itertools.product(..))).

like image 153
Andy Hayden Avatar answered Oct 05 '22 10:10

Andy Hayden