K. ossama
K. ossama

Reputation: 433

Regex with columns pandas

My question is how I can use the re to replace strings that included in a dataframe:

when I use the re.sub(), it gives me an error:

p = re.compile('New')
p.sub('old', df['Col1'])

Also, I tried using the for loop but the out put was unexpected and displaying the value of the first row in all the other rows:

for i in df['Col1']:
    p.sub('old', i)
    print(i)

I'm sure that I'm missing something.

Upvotes: 4

Views: 253

Answers (1)

jezrael
jezrael

Reputation: 863791

I think you can use str.replace, which works also with regex:

df = pd.DataFrame({'Col1':['sss old','dd','old']})
print (df)
      Col1
0  sss old
1       dd
2      old

df.Col1 = df.Col1.str.replace('old','new')
print (df)
      Col1
0  sss new
1       dd
2      new

Upvotes: 3

Related Questions