Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
K. ossama Avatar asked Nov 01 '25 11:11

K. ossama


1 Answers

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
like image 173
jezrael Avatar answered Nov 03 '25 00:11

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!