Str.replace方法返回属性错误.
dc_listings['price'].str.replace(',', '')
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
Run Code Online (Sandbox Code Playgroud)
以下是我的价格列的前5行.
此堆栈溢出线程建议检查我的列是否具有NAN值,但我的列中的值是否为NAN.
Ran*_*ndy 27
正如错误所述,您只能使用.str字符串列,并且您有一个float64.浮点数中不会有任何逗号,所以你拥有的东西不会真正做任何事情,但一般来说,你可以先抛出它:
dc_listings['price'].astype(str).str.replace...
Run Code Online (Sandbox Code Playgroud)
例如:
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
Run Code Online (Sandbox Code Playgroud)
小智 15
两种方式:
您可以使用series它来修复此错误。
dc_listings['price'].series.str.replace(',', '')
Run Code Online (Sandbox Code Playgroud)
如果series不起作用,您也可以使用apply(str)如下所示的替代方法:
dc_listings['price'].apply(str).str.replace(',', '')
Run Code Online (Sandbox Code Playgroud)