In pandas, how do I replace &
with '&' from all columns where &
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'?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With