I simply want the reverse operation of this command:
.reset_index(level=['ID'], inplace=True, col_level=1)
Now I have a dataframe:
DONNES_PRODUITS ... PYC_INTEGRES
ID UE PERIMETRE ... TVSU8 TV001 TV002
NUMBER ...
74 2 U4A MAIZON ... NaN NaN NaN
74 3 U4A MAIZON ... NaN NaN NaN
74 6 U4A MAIZON ... NaN NaN NaN
I want set ID as an index with NUMBER, for created a multi_index.
expected output:
DONNES_PRODUITS ... PYC_INTEGRES
UE PERIMETRE ... TVSU8 TV001 TV002
NUMBER ID ...
74 2 U4A MAIZON ... NaN NaN NaN
74 3 U4A MAIZON ... NaN NaN NaN
74 6 U4A MAIZON ...
I tried this solution:
result.set_index(['ID'], append=True)
I got the error message None of ['ID'] are in the columns
CodePudding user response:
You use .reset_index(level=['ID'], inplace=True, col_level=1)
so ID
is reset to the level 1 of multi-index columns, you can use
df = df.set_index([('', 'ID')], append=True)
print(df)
DONNES_PRODUITS
UE
NUMBER (, ID)
74 2 U4A
3 U4A
6 U4A
Or
df = (df.swaplevel(0,1,1)
.set_index(['ID'], append=True)
.swaplevel(0,1,1))
print(df)
DONNES_PRODUITS
UE
NUMBER ID
74 2 U4A
3 U4A
6 U4A