Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all string in all columns using pandas?

In pandas, how do I replace & with '&' from all columns where &amp could be in any position in a string?

For example, in column Title if there is a value 'Good & bad', how do I replace it with 'Good & bad'?

like image 513
bayman Avatar asked Jan 02 '23 04:01

bayman


1 Answers

Use replace with regex=True for substrings replacement:

df = pd.DataFrame({'A': ['Good & bad', 'BB', 'CC', 'DD', 'Good & bad'],
                   'B': range(5),
                   'C': ['Good & bad'] * 5})

print (df)
                A  B               C
0  Good & bad  0  Good & bad
1              BB  1  Good & bad
2              CC  2  Good & bad
3              DD  3  Good & bad
4  Good & bad  4  Good & bad

df = df.replace('&','&', regex=True)
print (df)
            A  B           C
0  Good & bad  0  Good & bad
1          BB  1  Good & bad
2          CC  2  Good & bad
3          DD  3  Good & bad
4  Good & bad  4  Good & bad

If want replace only one column:

df['A'] = df['A'].replace('&','&', regex=True)
print (df)
            A  B               C
0  Good & bad  0  Good & bad
1          BB  1  Good & bad
2          CC  2  Good & bad
3          DD  3  Good & bad
4  Good & bad  4  Good & bad
like image 191
jezrael Avatar answered Jan 04 '23 16:01

jezrael