Python Pandas: Add a level of MultIndexing

156 Views Asked by At

I have the following DataFrame:

enter image description here

where I want to add have an additional level of indexing for the columns such as shown in red.

I created the MultiIndex as follow:

MI = pd.MultiIndex(levels=[['trade_input', 'mae_function'], list(df)],
                   labels=[[0, 0, 1, 1, 1, 1], range(len(list(df)))],
                   names=['first', 'second'])

How do I add the MultiIndex to the existing DataFrame? How do I specify that it should be applied to the columns?

Here below the data and command to recreate the original DataFrame:

df = pd.DataFrame(data = dict, columns = ['entry_index', 'exit_index', 'direction', 'high', 'low', 'compar_tuples'])

dict = {'compar_tuples': {0: [(1, slice('1', '1', None))],
      1: [(1, slice('1', '2', None)), (2, slice('2', '2', None))],
      2: [(1, slice('1', '3', None)),
       (2, slice('2', '3', None)),
       (3, slice('3', '3', None))],
      3: [(1, slice('1', '4', None)),
       (2, slice('2', '4', None)),
       (3, slice('3', '4', None)),
       (4, slice('4', '4', None))],
      4: [(1, slice('1', '5', None)),
       (2, slice('2', '5', None)),
       (3, slice('3', '5', None)),
       (4, slice('4', '5', None)),
       (5, slice('5', '5', None))],
      5: [(1, slice('1', '6', None)),
       (2, slice('2', '6', None)),
       (3, slice('3', '6', None)),
       (4, slice('4', '6', None)),
       (5, slice('5', '6', None)),
       (6, slice('6', '6', None))],
      6: [(1, slice('1', '7', None)),
       (2, slice('2', '7', None)),
       (3, slice('3', '7', None)),
       (4, slice('4', '7', None)),
       (5, slice('5', '7', None)),
       (6, slice('6', '7', None)),
       (7, slice('7', '7', None))]},
     'direction': {0: 1, 1: -1, 2: -1, 3: -1, 4: -1, 5: -1, 6: -1},
     'entry_index': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0},
     'exit_index': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7},
     'high': {0: 1209.75,
      1: 1211.0,
      2: 1211.25,
      3: 1207.25,
      4: 1206.25,
      5: 1205.75,
      6: 1205.5},
     'low': {0: 1207.25,
      1: 1207.5,
      2: 1205.75,
      3: 1206.0,
      4: 1201.0,
      5: 1202.75,
      6: 1203.75}}
2

There are 2 best solutions below

0
On BEST ANSWER

Easiest way would be to use pd.concat with the keys parameter

ti_cols = df.columns[:2]
mae_cols = df.columns[2:]
pd.concat([df[ti_cols], df[mae_cols]], axis=1, keys=['trade_inputs', 'mae_function'])

enter image description here

But if you've gone through the trouble to make the multiindex, you can just assign it to the columns attribute

df.columns = MI
df

enter image description here

2
On
df.index = index

worked for me.