idt_tt
idt_tt

Reputation: 601

How can I remove all whitespace except one between words in pandas column

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

Answers (2)

badhusha muhammed
badhusha muhammed

Reputation: 491

Try This

 import re
 df["a"] = df["a"].apply(lambda x: re.sub(' +', ' ', x))

Upvotes: 2

Rakesh
Rakesh

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

Related Questions