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

后端 未结 8 1493
悲&欢浪女
悲&欢浪女 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:58

    This worked for me - applies it to the whole dataframe:

    def panda_strip(x):
        r =[]
        for y in x:
            if isinstance(y, str):
                y = y.strip()
    
            r.append(y)
        return pd.Series(r)
    
    df = df.apply(lambda x: panda_strip(x))
    

提交回复
热议问题