简体   繁体   中英

Pandas: Modify a particular level of Multiindex, using replace method several times

I am trying to use the replace method several times in order to change the indeces of a given level of a multiindex pandas' dataframe.

As seen here: Pandas: Modify a particular level of Multiindex , @John got a solution that works great so long the replace method is used once.

The problem is, that it does not work if I use this method several times. Eg

df.index = df.index.set_levels(df.index.levels[0].str.replace("dataframe_",'').replace("_r",' r'), level=0)

I get the following error message:

AttributeError: 'Index' object has no attribute 'replace'

What am I missing?

Use str.replace twice:

idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
df.index = df.index.set_levels(idx, level=0)

Another solution is converting to_series and then replace by dictionary:

d = {'dataframe_':'','_r':' r'}
idx = df.index.levels[0].to_series().replace(d)
df.index = df.index.set_levels(idx, level=0)

And solution with map and fillna , if large data and performance is important:

d = {'dataframe_':'','_r':' r'}
s = df.index.levels[0].to_series()
df.index = df.index.set_levels(s.map(d).fillna(s), level=0)

Sample :

df = pd.DataFrame({
        'A':['dataframe_','_r', 'a'],
        'B':[7,8,9],
        'C':[1,3,5],

}).set_index(['A','B'])

print (df)
              C
A          B   
dataframe_ 7  1
_r         8  3
a          9  5

d = {'dataframe_':'','_r':' r'}
idx = df.index.levels[0].to_series().replace(d)
df.index = df.index.set_levels(idx, level=0)
print (df)
      C
A  B   
   7  1
 r 8  3
a  9  5

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