10

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'
2
  • The error message seems pretty clear to me? Commented Apr 7, 2019 at 8:25
  • It seems that you have a float type in the field of "test" in the data frame Commented Apr 7, 2019 at 8:28

4 Answers 4

8

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 :

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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"]]

Comments

2

As the indicated in the error message, text must be string. You may try changing data type:

text = str(text) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.