Reputation: 157
I have a df that looks like this:
2019 2018
Sally -6461 -6340
Brian 7139 7200
rebecca 1337 1067
mark 10922 11128
toto 12936 13054
and list given as:
listVal = ["Sally","rebecca"]
for the row that is in listVal
, I would like to change the name by adding 00
So that final df looks like this:
2019 2018
Sally00 -6461 -6340
Brian 7139 7200
rebecca00 1337 1067
mark 10922 11128
toto 12936 13054
Is there one line code that achieves this without using for loop like below?
for val in listVal:
df.index = df.index.str.replace(val, val+'00')
Upvotes: 1
Views: 396
Reputation: 7693
You can use where
with isin
df.index = df.index.where(~df.index.isin(listVal), df.index+'00')
df
2019 2018
Sally00 -6461 -6340
Brian 7139 7200
rebecca00 1337 1067
mark 10922 11128
toto 12936 13054
Upvotes: 1
Reputation: 1098
If the Sally, Brian, etc. is index names, then pandas have builtin function for renaming column and row names
df_new = df.rename(index={'Sally': 'Sally00','rebecca':'rebecca00'})
You can use any list to dict methods to programatically create the new names for the rows.
As @maow suggest you can use the following.
df.rename(index={val: val+'00' for val in ['Sally', 'rebecca']})
Upvotes: 0