2

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?

1
  • You probably have to build a new index, since index are mostly immutable Commented Mar 9, 2022 at 12:55

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

this code should work either:

df.index.set_levels([26,28], level='season_id', inplace=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.