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

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

    The "data['values'].str.strip()" answer above did not work for me, but I found a simple work around. I am sure there is a better way to do this. The str.strip() function works on Series. Thus, I converted the dataframe column into a Series, stripped the whitespace, replaced the converted column back into the dataframe. Below is the example code.

    import pandas as pd
    data = pd.DataFrame({'values': ['   ABC   ', '   DEF', '  GHI  ']})
    print ('-----')
    print (data)
    
    data['values'].str.strip()
    print ('-----')
    print (data)
    
    new = pd.Series([])
    new = data['values'].str.strip()
    data['values'] = new
    print ('-----')
    print (new)
    

提交回复
热议问题