Reputation: 121
I have a column which has text in it. I have to replace (':',' ').
When I am running this code:
df["text"] = [x.replace(':',' ') for x in df["text"]]
I am facing the this error:
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'
Upvotes: 10
Views: 48626
Reputation: 863166
In my opinion problem is missing value in column, so use pandas methods Series.str.replace
or Series.replace
instead list comprehension:
df["text"] = df["text"].str.replace(':',' ')
Or:
df["text"] = df["text"].str.replace(':',' ', regex=True)
Solution with list comprehension is possible, only need if-else statement for test strings:
df["text"] = [x.replace(':',' ') if isinstance(x, str) else x for x in df["text"]]
Sample:
df = pd.DataFrame({'text':['qq:ww','e:', np.nan]})
df["text"] = df["text"].str.replace(':',' ')
print (df)
text
0 qq ww
1 e
2 NaN
Upvotes: 4
Reputation: 31
As the indicated in the error message, text must be string. You may try changing data type:
text = str(text)
Upvotes: 2
Reputation: 620
The error is pretty clear. you are trying to replace characters in a float. x probably is a float. you might want to do str(x) which gets you
f["text"] = [str(x).replace(':',' ') for x in df["text"]]
but i can't see a situation where a float contains a :
Upvotes: 8
Reputation: 113
Please try writing adding above line to your code and let me know if that works for you.
df["text"] = df["text"].astype(str)
df["text"] = [x.replace(':',' ') for x in df["text"]]
Upvotes: 3