首页 > 解决方案 > AttributeError:只能使用带有字符串值的 .str 访问器

问题描述

这不是骗子!我已经解决了所有相关问题,但他们没有回答我的问题。

我正在使用标准方法从 pandas 字符串列中去除空格,如下所述

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

但不断得到:

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具有字符串值的访问器!”)
返回 inferred_dtype

AttributeError:只能使用带有字符串值的 .str 访问器!

当我运行时,print(df_obj .dtypes)我将所有列列为“ object”。所以有什么问题?

熊猫版本:'1.1.4'

标签: pythonpandas

解决方案


通过修改 2. 行将列转换为字符串来解决它:

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

我以前从来没有在列上使用过它。object我认为对象列默认是字符串...


推荐阅读