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

后端 未结 8 1492
悲&欢浪女
悲&欢浪女 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条回答
  •  Happy的楠姐
    2020-12-04 12:36

    You could use pandas' Series.str.strip() method to do this quickly for each string-like column:

    >>> data = pd.DataFrame({'values': ['   ABC   ', '   DEF', '  GHI  ']})
    >>> data
          values
    0     ABC   
    1        DEF
    2      GHI  
    
    >>> data['values'].str.strip()
    0    ABC
    1    DEF
    2    GHI
    Name: values, dtype: object
    

提交回复
热议问题