Replace a value in MultiIndex (pandas)

2019-07-13 20:46发布

问题:

In the following DataFrame: How can I replace ["x2", "Total"] with ["x2", "x2"] leaving x1 as is?

l1           900    902    912     913    916     
l2           ИП ПС  ИП ПС  ИП  ПС  ИП ПС  ИП ПС  
i1    i2                                      
x1    Total  10  6   3  3  10  16   2  9   3  8  
x2    Total   1  0   0  0   0   0   0  0   0  0  

.rename will replace all "Total" values, not just the one I need.

回答1:

Assuming your dataframe is called df the following code will perform your desired substitution by replacing the existing index with a modified index.

index = df.index
names = index.names
index = df.index.tolist()[:1]+[('x2','x2')]  
df.index = pd.MultiIndex.from_tuples(index, names = names)

Or you can directly modify the inner level of the index:

df.index.set_levels([u'Total', u'x2'],level=1,inplace=True)
df.index.set_labels([0, 1],level=1,inplace=True)

You can also use level='i2' in place of level=1