Skip to content Skip to sidebar Skip to footer

Custom Sorting Columns In Multi Level Pandas Dataframe

Background I have a big data frame with 2 levels columns, but 1 level rows, and I am trying to sort it as follows: level 0: alphabetically; level 1: custom sort. Example import pan

Solution 1:

You can achieve this using reindex_axis, this accepts a labels arg, axis and level:

In [20]:
df = df.reindex_axis(list('FML'), axis=1, level=1)
df

Out[20]:
   A        B        C      
   F  M  L  F  M  L  F  M  L
g  316619027
h  527255138
i  138726649
j  349153351
k  551534562

Thanks to @Nickli Maveli you can also use reindex to achieve the same:

In [22]:
df = df.reindex(columns=list('FML'), level=1)
df

Out[22]:
   A        B        C      
   F  M  L  F  M  L  F  M  L
g  316619027
h  527255138
i  138726649
j  349153351
k  551534562

Solution 2:

Setting index on dataframe creation

If you do not want to change the dataframe afterwards, you can give the pd.DataFrame constructor an index where you define the order already.

Explicit solution

columns = pd.Index([('A', 'F'), ('A', 'M'), ('A', 'L'), ('B', 'F'), ('B', 'M'), ('B', 'L'),('C', 'F'), ('C', 'M'), ('C', 'L')])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)

Composite solution

columns = pd.Index([(level_0, level_1) forlevel_0in"ABC"forlevel_1in"FML"])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)

Both gives

AB        C      
   F  M  L  F  M  L  F  M  L
g  316619027
h  527255138i138726649
j  349153351
k  551534562

Post a Comment for "Custom Sorting Columns In Multi Level Pandas Dataframe"