How to do string replacement on specific rows in a pandas series

Viewed 18

I have a pandas series, a1:

0              Front Bumper
1               Rear Bumper
2        Right Front Mirror
3        Right Front Mirror
4               Rear Bumper
5        Right Front Mirror

I need to replace some parts of those strings, on specific rows. I have a Boolean list:

to_replace = [True, False, False, False, True, False]

Which I want to use as a filter to replace the word "Bumper" only on rows 0 and 4. I thought that this should work:

a1.loc[to_replace].str.replace("Bumber", "Wing")

But it did nothing. What an I doing wrong?

1 Answers

You need to assign the result back to Series:

a1.loc[to_replace] = a1.loc[to_replace].str.replace("Bumper", "Wing")
print(a1)

Prints:

0            Front Wing
1           Rear Bumper
2    Right Front Mirror
3    Right Front Mirror
4             Rear Wing
5    Right Front Mirror
dtype: object
Related