How to replace all string in all columns using pandas?

Question:

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’?

Asked By: bayman

||

Answers:

Try this

df['Title'] = titanic_df['Title'].replace("&", "&")

Answered By: Songtham T.

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
Answered By: jezrael

Try this also worked for me

df['A'] = [i.replace('&','&') for i in list(df['A'])]
Answered By: Lokeshwar G
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.