close

How to solve the Attribute error ‘float’ object has no attribute ‘split’ in python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to solve the Attribute error ‘float’ object has no attribute ‘split’ in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to solve the Attribute error ‘float’ object has no attribute ‘split’ in python?

  1. How to solve the Attribute error 'float' object has no attribute 'split' in python?

    split is being used here as a method of Python's built-in str class. Your error indicates one or more values in df['content'] is of type float. This could be because there is a null value, i.e. NaN, or a non-null float value.

  2. solve the Attribute error 'float' object has no attribute 'split' in python

    split is being used here as a method of Python's built-in str class. Your error indicates one or more values in df['content'] is of type float. This could be because there is a null value, i.e. NaN, or a non-null float value.

Method 1

The error points to this line:

df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in x.split() \
                                    if x not in stop_words))

split is being used here as a method of Python’s built-in str class. Your error indicates one or more values in df['content'] is of type float. This could be because there is a null value, i.e. NaN, or a non-null float value.

One workaround, which will stringify floats, is to just apply str on x before using split:

df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in str(x).split() \
                                    if x not in stop_words))

Alternatively, and possibly a better solution, be explicit and use a named function with a try / except clause:

def converter(x):
    try:
        return ' '.join([x.lower() for x in str(x).split() if x not in stop_words])
    except AttributeError:
        return None  # or some other value

df['content'] = df['content'].apply(converter)

Since pd.Series.apply is just a loop with overhead, you may find a list comprehension or map more efficient:

df['content'] = [converter(x) for x in df['content']]
df['content'] = list(map(converter, df['content']))

Method 2

split() is a python method which is only applicable to strings. It seems that your column “content” not only contains strings but also other values like floats to which you cannot apply the .split() mehthod.

Try converting the values to a string by using str(x).split() or by converting the entire column to strings first, which would be more efficient. You do this as follows:

df['column_name'].astype(str)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read