I have a huge dataframe with 126 columns. I want to add an extra level (multiindex) where i would like to have 5 categories, so each of 126 columns would fall under the corresponding category. I have found many solutions with defining levels and writing down all columns you want to append to that level, which is really time consuming since i have to group 126 columns. Is there a faster way to do this? For example with slicing columns like .iloc[:,9:44]
, since i want to group those 35 columns to one category?
Dataframe looks like this:
df
a b c... d e f... g h i... j k l... n=126
1 1.0 1.0 1.0 2.0 3.0 2.0 1.0 1.0 1.0 2.0 3.0 2.0
2 4.0 5.0 4.0 4.0 8.0 4.0 4.0 5.0 4.0 4.0 8.0 4.0
3 6.0 1.0 6.0 7.0 8.0 7.0 6.0 1.0 6.0 7.0 8.0 7.0
The solution would look like this:
df2
A | B | C | D n=5
a b c... | d e f... | g h i... | j k l n=126
1 1.0 1.0 1.0 2.0 3.0 2.0 1.0 1.0 1.0 2.0 3.0 2.0
2 4.0 5.0 4.0 4.0 8.0 4.0 4.0 5.0 4.0 4.0 8.0 4.0
3 6.0 1.0 6.0 7.0 8.0 7.0 6.0 1.0 6.0 7.0 8.0 7.0