0

This is not a dupe! I've been through all related questions and they don't answer my problem.

I'm using standard method for stripping spaces from pandas string columns as explained here:

df_obj = df.select_dtypes(['object'])
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())

But keep getting:

c:\users\user\appdata\local\programs\python\python37\lib\site-packages\pandas\core\strings.py in _validate(data) if inferred_dtype not in allowed_types: raise AttributeError("Can only use .str accessor with string values!")
return inferred_dtype

AttributeError: Can only use .str accessor with string values!

And when I run print(df_obj .dtypes) I get all columns listed as 'object'. So what's the problem?

Pandas version: '1.1.4'

Hrvoje
  • 13,566
  • 7
  • 90
  • 104

1 Answers1

0

Solved it by converting columns to string by modifying 2. line:

df[df_obj.columns] = df_obj.apply(lambda x: x.astype('str').str.strip())

Never before have I had to use this on object column..I thought object columns where strings by default...

Hrvoje
  • 13,566
  • 7
  • 90
  • 104