I have a dataframe like the following:
and I want to group the answers like the following
I tried to use multindex, but it won’t work.
CodePudding user response:
You can use pandas.MultiIndex.from_array
to manually craft your custom index:
new_level = ['GROUP1', 'GROUP1', 'GROUP1', 'GROUP2', 'GROUP2', 'GROUP3', 'GROUP3']
df.columns = pd.MultiIndex.from_arrays([new_level, df.columns])
example input:
A B C D E
0 X X X X X
output:
>>> df.columns = pd.MultiIndex.from_arrays([[1,1,2,2,3], df.columns])
>>> df
1 2 3
A B C D E
0 X X X X X