Tristan Forward Tristan Forward - 1 month ago 9
Python Question

Python Pandas multi-index values not moving over in pivot table

I have the following Python Pandas dataframe:

enter image description here

import pandas as pd

I then run this code to format the table how I want:

col_mapping = {'Central Mixedwood (CM)': ['CM Area (ha)', 'CM % of LSA*'],
'Lower Boreal Highlands (LBH)': ['LBH Area (ha)','LBH % of LSA'],
'Total LSA': ['Total Area (ha)', 'Total Area % of LSA']}
cols = [(k,v) for k,sublist in col_mapping.items()
for v in sublist]
p_table.columns = pd.MultiIndex.from_tuples(cols)
p_table


Which Yields:
enter image description here

The Labels are all in the correct spot however the values have not shifted to the correct column they remain the same as before, How do I fix this?

Answer

You need to re-index the axis first:

>>> idx = pd.MultiIndex.from_tuples(cols)
>>> p_table = p_table.reindex_axis(idx.get_level_values(1), axis=1)
>>> p_table.columns = idx
Comments