首页 > 解决方案 > 替换字符串时出现“AttributeError:'float'对象没有属性'replace'”错误

问题描述

我有一个列,其中包含文本。我必须替换(':','')。

当我运行此代码时:

df["text"] = [x.replace(':',' ') for x in df["text"]]

我正面临这个错误:

AttributeError: 'float' object has no attribute 'replace'

AttributeError                            Traceback (most recent call 
last)
<ipython-input-13-3c116e6f21e2> in <module>
  1 #df["text"] = df["text"].astype(str)
----> 2 df["text"] = [x.replace(':',' ') for x in df["text"]]

<ipython-input-13-3c116e6f21e2> in <listcomp>(.0)
  1 #df["text"] = data["NOTES_ENT"].astype(str)
----> 2 df["text"] = [x.replace(':',' ') for x in df["text"]]

AttributeError: 'float' object has no attribute 'replace'

标签: pythonpython-3.xpandas

解决方案


错误很明显。您正在尝试替换浮点数中的字符。x 可能是一个浮点数。你可能想做 str(x) 这让你

f["text"] = [str(x).replace(':',' ') for x in df["text"]]

但我看不到浮点数包含 a 的情况:


推荐阅读