【问题标题】:AttributeError: Can only use .str accessor with string valuesAttributeError:只能使用带有字符串值的 .str 访问器
【发布时间】:2021-03-18 14:06:15
【问题描述】:

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

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

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 如果 inferred_dtype 不在 _validate(data) 中 allowed_types: raise AttributeError("Can only use .str accessor with string values!")
返回 inferred_dtype

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

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

熊猫版本:'1.1.4'

【问题讨论】:

    标签: python pandas


    【解决方案1】:

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

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

    我以前从未在object 列上使用它。我认为对象列默认为字符串...

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 2018-12-22
      • 2017-06-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多