替换字符串时出现“AttributeError:'float'对象没有属性'replace'”错误

ani*_*nil 9 python python-3.x pandas

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

当我运行这段代码时:

df["text"] = [x.replace(':',' ') for x in df["text"]]
Run Code Online (Sandbox Code Playgroud)

我面临这个错误:

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'
Run Code Online (Sandbox Code Playgroud)

jon*_*han 7

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

f["text"] = [str(x).replace(':',' ') for x in df["text"]]
Run Code Online (Sandbox Code Playgroud)

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


小智 3

请尝试将以上行添加到您的代码中,并让我知道这是否适合您。

df["text"] = df["text"].astype(str)
df["text"] = [x.replace(':',' ') for x in df["text"]]
Run Code Online (Sandbox Code Playgroud)