Strip / trim all strings of a dataframe

后端 未结 6 910
夕颜
夕颜 2020-11-27 13:04

Cleaning the values of a multitype data frame in python/pandas, I want to trim the strings. I am currently doing it in two instructions :

import pandas as pd         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 13:27

    You can use DataFrame.select_dtypes to select string columns and then apply function str.strip.

    Notice: Values cannot be types like dicts or lists, because their dtypes is object.

    df_obj = df.select_dtypes(['object'])
    print (df_obj)
    0    a  
    1    c  
    
    df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
    print (df)
    
       0   1
    0  a  10
    1  c   5
    

    But if there are only a few columns use str.strip:

    df[0] = df[0].str.strip()
    

提交回复
热议问题