Reputation: 601
I have a pandas dataframe which looks like this:
pd.DataFrame({'a':['AB CD', 'EF GH', 'IJ KL', 'MNO P', 'Q RS']})
a
0 AB CD
1 EF GH
2 IJ KL
3 MNO P
4 Q RS
I want to remove all whitespace between words except for one. How can I do this?
resulting dataframe should look like this:
a
0 AB CD
1 EF GH
2 IJ KL
3 MNO P
4 Q RS
Upvotes: 1
Views: 448
Reputation: 491
Try This
import re
df["a"] = df["a"].apply(lambda x: re.sub(' +', ' ', x))
Upvotes: 2
Reputation: 82785
Using str.split()
with agg(" ".join)
Ex:
df = pd.DataFrame({'a':['AB CD', 'EF GH', 'IJ KL', 'MNO P', 'Q RS']})
df['a'] = df['a'].str.split().agg(" ".join)
print(df)
Output:
a
0 AB CD
1 EF GH
2 IJ KL
3 MNO P
4 Q RS
Upvotes: 4