Pythonic/efficient way to strip whitespace from every Pandas Data frame cell that has a stringlike object in it

后端 未结 8 1504
悲&欢浪女
悲&欢浪女 2020-12-04 12:05

I\'m reading a CSV file into a DataFrame. I need to strip whitespace from all the stringlike cells, leaving the other cells unchanged in Python 2.7.

Here is what I\

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 12:39

    I found the following code useful and something that would likely help others. This snippet will allow you to delete spaces in a column as well as in the entire DataFrame, depending on your use case.

    import pandas as pd
    
    def remove_whitespace(x):
        try:
            # remove spaces inside and outside of string
            x = "".join(x.split())
    
        except:
            pass
        return x
    
    # Apply remove_whitespace to column only
    df.orderId = df.orderId.apply(remove_whitespace)
    print(df)
    
    
    # Apply to remove_whitespace to entire Dataframe
    df = df.applymap(remove_whitespace)
    print(df)
    

提交回复
热议问题