pandas 属性错误:只能对字符串值使用.str访问器,该访问器在panda中使用np.object_ dtype

jhkqcmku  于 2022-12-02  发布在  其他
关注(0)|答案(4)|浏览(80)

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值。

ljsrvy3e

ljsrvy3e1#

正如错误所述,只能对字符串列使用.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
zyfwsgd6

zyfwsgd62#

两种方式:
1.您可以使用series来修正这个错误。

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

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

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

x7rlezfr3#

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

bybem2ql

bybem2ql4#

Randysolution来处理将整个列更改为str类型的问题。(如NAlistdict自定义类),并希望将来过滤这些特殊值,我建议您创建自己的函数,然后将其apply仅应用于str value,如下所示:

dc_listings['price'] = dc_listings['price'].apply(
   lambda x: x.replace(',', '') if type(x) is str else x
)

或者更清楚地使用def

def replace_substring_or_return_value(value):
  if type(value) is str: return x.replace(',', '')
  else: return value

dc_listings['price'] = dc_listings['price'].apply(
      replace_substring_or_return_value
)

尽管如此这可能是一个不好的做法,因为您应该对列中的每个值使用**the same data type**

相关问题