Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove unwanted spaces from a cell using pandas?

I have the below mentioned data.

,name,link,address
0,Aasia Steel Industrial Group,http://www.aasiasteel.com/,"
Address

                                        1 
                                                Saudi Arabia 
                                    "
1,ADES,http://investors.adihgroup.com/,"
Address

                                        Al-Kifah Tower 
                                                King Fahad Road 
                                                    Dhahran 
                                                Saudi Arabia 
                                    "
2,AEC,https://www.aecl.com,"
Address

                                        King Khalid International Airport. 
                                                Industrial Estate P.O.Box 90916, 
                                                    Riyadh 11623, 
                                                    Saudi Arabia 
                                    "

There is a lot of unwanted spaces. I tries using the below functions but I am not able to clean my cells.

df['address']=df.address.str.strip()

In the console the the output is address column follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

\nAddress\r\n\r\n\t\t\t\t\t\t\t\t\t\tAl-Kifah

>Solution :

df['address'].apply(lambda x:' '.join(x.split()))

If the column has other variable excpet string then we can use:

df['address'].apply(lambda x:' '.join(x.split()) if hasattr(x,'lower') else x)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading