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

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

    Stumbled onto this question while looking for a quick and minimalistic snippet I could use. Had to assemble one myself from posts above. Maybe someone will find it useful:

    data_frame_trimmed = data_frame.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题