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

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

    We want to:

    1. Apply our function to each element in our dataframe - use applymap.

    2. Use type(x)==str (versus x.dtype == 'object') because Pandas will label columns as object for columns of mixed datatypes (an object column may contain int and/or str).

    3. Maintain the datatype of each element (we don't want to convert everything to a str and then strip whitespace).

    Therefore, I've found the following to be the easiest:

    df.applymap(lambda x: x.strip() if type(x)==str else x)

提交回复
热议问题