【问题标题】:AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandasAttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
【发布时间】:2022-01-01 21:22:23
【问题描述】:

Str.replace 方法返回属性错误。

dc_listings['price'].str.replace(',', '')
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

这是我的价格列的前 5 行。

此堆栈溢出thread recommends 以检查我的列是否具有 NAN 值,但我的列中的值不是 NAN。

【问题讨论】:

  • 你的专栏是float,所以你不能在上面使用字符串方法。此外,由于它是一个浮点列,因此它不会包含 ','

标签: python pandas


【解决方案1】:

两种方式:

  1. 您可以使用series 来修复此错误。

    dc_listings['price'].series.str.replace(',', '')
    

  1. 如果series 不起作用,您也可以替换使用apply(str),如下所示:

    dc_listings['price'].apply(str).str.replace(',', '')
    

【讨论】:

    【解决方案2】:

    如果 price 是 dtype float 64 则数据不是字符串。 你可以试试dc_listings['price'].apply(function)

    【讨论】:

      【解决方案3】:

      由于错误状态,您只能将.str 与字符串列一起使用,并且您有一个float64。浮点数中不会有任何逗号,所以你所拥有的不会真正做任何事情,但一般来说,你可以先转换它:

      dc_listings['price'].astype(str).str.replace...
      

      例如:

      In [18]: df
      Out[18]:
                a         b         c         d         e
      0  0.645821  0.152197  0.006956  0.600317  0.239679
      1  0.865723  0.176842  0.226092  0.416990  0.290406
      2  0.046243  0.931584  0.020109  0.374653  0.631048
      3  0.544111  0.967388  0.526613  0.794931  0.066736
      4  0.528742  0.670885  0.998077  0.293623  0.351879
      
      In [19]: df['a'].astype(str).str.replace("5", " hi ")
      Out[19]:
      0    0.64 hi 8208 hi  hi 4779467
      1          0.86 hi 7231174332336
      2            0.04624337481411367
      3       0. hi 44111244991 hi 194
      4          0. hi 287421814241892
      Name: a, dtype: object
      

      【讨论】:

      • 这成功了!我以为价格列是“字符串”。
      • 这对我有用,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多