fred.schwartz
fred.schwartz

Reputation: 2155

find and replace pandas

I have a dataframe with names

aaaaxxxdddd
dddxbbb
aaaaxxxcccc

I want to say if string contains 'xxx' then replace 'a' with 'b'

giving

bbbbxxxdddd
dddxbbb
bbbbxxxcccc

I have the 2 bits of code but can't figure out how to put them together

if df['col'].str.contains('xxx')
 df['col'] = df['col'].map(lambda x: str.replace(x, 'a',"b"))

Upvotes: 0

Views: 110

Answers (1)

jezrael
jezrael

Reputation: 862511

Use DataFrame.loc with filtering rows by boolean mask in both size for improve performance - replace only for fitered rows:

m = df['col'].str.contains('xxx')
df.loc[m, 'col'] = df.loc[m, 'col'].str.replace('a',"b")

print (df)
           col
0  bbbbxxxdddd
1      dddxbbb
2  bbbbxxxcccc

Another solution is use list comprehension:

df['col'] = [x.replace('a',"b") if 'xxx' in x else x for x in df['col']]

Upvotes: 3

Related Questions