简体   繁体   中英

Replace a value in MultiIndex (pandas)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM