Let's say that I have a pandas.DataFrame with a hierarchical index in the columns as follows:
import pandas as pd columns = pd.MultiIndex.from_product([list('AB'), list('ab')]) df = pd.DataFrame(np.arange(8).reshape((2,4)), columns=columns) print df
From [1]:
AB abab 0 0 1 2 3 1 4 5 6 7
I would like to flatten the column index so that it looks like this:
Aa Ab Ba Bb 0 0 1 2 3 1 4 5 6 7
I tried
def flatten(col): col.name = ''.join(col.name) return col df.apply(f)
but it just ignored the changed name of the new columns.
source share