Issue
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'?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.