In pandas the object type is used when there is not a clear distinction between the types stored in the column.

So, I guess that in your column, some objects are float type and some objects are str type. Or maybe, you are also dealing with NaN objects, NaN objects are float objects.

a) Convert the column to string: Are you getting your DataFrame from a CSV or XLS format file? Then at the moment of reading the file, you can specify that that column is an str type or just make the type conversion of the column you are dealing with.

b) After that, you can apply the string changes and/or deal with the NaN objects.

c) Finally, you transform your column into float type`.

Answer from omar on Stack Exchange
Discussions

str.find returns dtype: float64
str.find fails to return integers As per the docs it should return Series/Index of integer values Code Sample, a copy-pastable example if possible df[:5] 0 1 0 ZAR12015 FastEthernet2/0/38 1 AFA1228... More on github.com
🌐 github.com
2
February 1, 2017
'NoneType' object has no attribute 'loc'
df = df.drop(index, inplace = True) Using inplace = True changes the return value of df.drop() to None. Either don't use inplace df = df.drop(index) Or don't try to assign the return value back to the dataframe df.drop(index, inplace = True) More on reddit.com
🌐 r/learnpython
5
3
February 14, 2024
python - Replacing column value by NaN when another column has a certain value in pandas - Stack Overflow
I have the following data frame: Month,Value1,Value2 02,1,10 03,2,2 04,3,12 In this Dataframe I wish to replace Value1 by NaN each time Value2 is More on stackoverflow.com
🌐 stackoverflow.com
Python Script (Labs) Error No attribute Loc
Hello, I am trying to run a piece of code in python labs but it keeps throwing me this error Thanks More on forum.knime.com
🌐 forum.knime.com
1
0
September 2, 2022
🌐
GitHub
github.com › pandas-dev › pandas › issues › 15279
str.find returns dtype: float64 · Issue #15279 · pandas-dev/pandas
February 1, 2017 - df[:5] 0 1 0 ZAR12015 FastEthernet2/0/38 1 AFA12286 FastEthernet4/0/22 2 CAA12029 FastEthernet2/0/35 3 IFAA2302 FastEthernet4/0/14 4 HFQ12009 FastEthernet5/38 df.loc[:,"1"].str.find("Ether") 6982 4.0 6983 4.0 6984 4.0 Name: 1, dtype: float64 df.loc[:,"1"].apply( lambda x : x[x.find("Ether"):]) AttributeError Traceback (most recent call last) <ipython-input-39-73570bc63928> in <module>() ----> 1 df.loc[:,"1"].apply( lambda x : x[x.find("Ether"):]) C:\Users\X91437\Documents\Program Files\Anaconda\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 2290 else:
Author   littlegreenbean33
🌐
Reddit
reddit.com › r/learnpython › 'nonetype' object has no attribute 'loc'
r/learnpython on Reddit: 'NoneType' object has no attribute 'loc'
February 14, 2024 -

I am learning pandas right now and I am working on a little project for fun with Netflix movies. I am trying to filter the dataset, so it contains only movies with a genre specified by the user; however, I am getting the following error for this chunk of code after an input has been made:

genre = input("Genre: ")

for index in df.index:
    if df.loc[index, genre] == 0:
        df = df.drop(index, inplace = True)
print(df.head())

if df.loc[index, genre] == 0:
^^^^^^
AttributeError: 'NoneType' object has no attribute 'loc'

Find elsewhere
🌐
GitHub
github.com › BaselAbujamous › clust › issues › 29
Data pre-processing, AttributeError: 'float' object has no attribute 'replace' · Issue #29 · BaselAbujamous/clust
January 25, 2019 - You must be signed in to change notification settings · Fork 36 · Star 165 · New issueCopy link · New issueCopy link · Closed · Closed · Data pre-processing, AttributeError: 'float' object has no attribute 'replace'#29 · Copy link · Labels · Answeredbug ·
Author   johnsolk
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-float-object-has-no-attribute
AttributeError: 'float' object has no attribute 'X' (Python) | bobbyhadz
If you print() the value you are accessing the attribute on, it will be a float. To solve the error, you need to track down where exactly you are setting the value to a float in your code and correct the assignment.
Top answer
1 of 3
26

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']))
2 of 3
9

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)
🌐
Educative
educative.io › answers › what-is-the-dataframeloc-attribute-in-pandas
What is the DataFrame.loc attribute in Pandas?
In Pandas, the loc attribute of a DataFrame is used to access a group of rows and columns of a DataFrame by using their labels.
🌐
CSDN
devpress.csdn.net › python › 63045b8d7e6682346619a75f.html
How to solve the Attribute error 'float' object has no attribute 'split' in python?_python_Mangs-Python
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)
🌐
freeCodeCamp
forum.freecodecamp.org › python
Bug found in Data Analysis Example B Lecture File - Python - The freeCodeCamp Forum
July 7, 2022 - In the Lecture_2.ipynb example code is: df['rental_gain_return'].mean().round(2) results in: AttributeError: 'float' object has no attribute 'round' This is incorrect and should be: round(df['rental_gain_return'].mean(),2) Same with the median as well. Version of python: 3.10.5 Version of pandas: 1.4.2-1
🌐
Reddit
reddit.com › r/scipy › use of sympy.log seems to cause attributeerror: 'float' object has no attribute 'gradient' , why?
r/scipy on Reddit: Use of sympy.log seems to cause AttributeError: 'Float' object has no attribute 'gradient' , why?
February 12, 2019 -

I'm doing minimization using barrier method based on scipy.optimize.minimize.

My objective function has one term, which is supposed to be inside a logarithm. I've tried running the program without the log and it works fine.

However when I add the sympy.log, then I get:

AttributeError: 'Float' object has no attribute 'gradient' 

What is wrong?

More traceback:

Traceback (most recent call last):
  File "C:\Users\matti\AppData\Roaming\Python\Python36\site-packages\scipy\optimize\_minimize.py", line 484, in minimize
    **options)
  File "C:\Users\matti\AppData\Roaming\Python\Python36\site-packages\scipy\optimize\optimize.py", line 1551, in _minimize_newtoncg
    b = -fprime(xk)
  File "C:\Users\matti\AppData\Roaming\Python\Python36\site-packages\scipy\optimize\optimize.py", line 292, in function_wrapper
    return function(*(wrapper_args + args))
  File "C:\Users\matti\AppData\Local\Programs\Python\Python36\lib\site-packages\ad\__init__.py", line 1090, in grad
    return numpy.array(ans.gradient(list(xa)))
AttributeError: 'Float' object has no attribute 'gradient'

Also, replacing the sympy.log with Python's standard math.log seems to work.

Something buggy with sympy?

🌐
GitHub
github.com › teese › eccpy › issues › 16
'float' object has no attribute 'max' · Issue #16 · teese/eccpy
June 27, 2021 - ~/opt/anaconda3/lib/python3.8/site-packages/eccpy/curvefit.py in calc_EC50(fn, dff, settings, t20) 1107 # set the x-axis limit so that the legend does not hide too many data points 1108 # find the maximum dose concentration in the whole experiment for that day -> 1109 maxAC = x_orig.max().max() 1110 # # obtain the variable altering the extension of the x-axis 1111 # x_axis_extension_after_dosemax_in_summ_plot = dff.loc[fn, "x-axis extension in summary fig_0"] AttributeError: 'float' object has no attribute 'max'
Author   nomadkml