This is may DataFrame (two columns : name
and age
and two indices : player_id
and season_id
).
name | age | ||
---|---|---|---|
player_id | season_id | ||
991 | 28 | Fabio | 33 |
1028 | 28 | Luigi | 25 |
I want to change a value inside the MultiIndex in this way:
name | age | ||
---|---|---|---|
player id | season id | ||
991 | 26 | Fabio | 33 |
1028 | 28 | Luigi | 25 |
I've tried different ways without any effect.
df.loc[[(991,28)]].index.set_levels = (991,26)
df.loc[[(991,28)]].index.set_levels([991,26], inplace=True)
df.loc[[(991,28)]].index = df.loc[[(991,28)]].index.set_levels([991,26])
Has someone some suggests?
CodePudding user response:
Use list comprehension with if-else
and recreate df.index
:
df.index = pd.MultiIndex.from_tuples([(991,26) if x == (991,28) else x for x in df.index],
names=df.index.names)
print (df)
name age
player_id season_id
991 26 Fabio 33
1028 28 Luigi 25
CodePudding user response:
this code should work either:
df.index.set_levels([26,28], level='season_id', inplace=True)