I have a dataframe with a multi index. I want to change the value of the second index under certain conditions for the first index. I found a similar (but different) question here: Replace the value in MultiIndex (pandas)
which does not answer my question, because it was about changing one row, and the solution passed the value of the first index (which also did not need to be changed). In my case, I am dealing with several lines, and I could not adapt this solution to my case.
Below is a minimal example of my data. Thank!
import pandas as pd
import numpy as np
consdf=pd.DataFrame()
for mylocation in ['North','South']:
for scenario in np.arange(1,4):
df= pd.DataFrame()
df['mylocation'] = [mylocation]
df['scenario']= [scenario]
df['this'] = np.random.randint(10,100)
df['that'] = df['this'] * 2
df['something else'] = df['this'] * 3
consdf=pd.concat((consdf, df ), axis=0, ignore_index=True)
mypiv = consdf.pivot('mylocation','scenario').transpose()
level_list =['this','that']
mypiv.iloc[mypiv.index.get_level_values(0).isin(level_list)].index.set_levels([np.nan], level =1, inplace=True)
The last line does not work: I get:
ValueError: On level 1, label max (2) >= length of level (1). NOTE: this index is in an inconsistent state
source
share