To pickup from the comment: "I was doing this:"

df = [df.hc== 2]

What you create there is a "mask": an array with booleans that says which part of the index fulfilled your condition.

To filter your dataframe on your condition you want to do this:

df = df[df.hc == 2]

A bit more explicit is this:

mask = df.hc == 2
df = df[mask]

If you want to keep the entire dataframe and only want to replace specific values, there are methods such replace: Python pandas equivalent for replace. Also another (performance wise great) method would be creating a separate DataFrame with the from/to values as column and using pd.merge to combine it into the existing DataFrame. And using your index to set values is also possible:

df[mask]['fname'] = 'Johnson'

But for a larger set of replaces you would want to use one of the two other methods or use "apply" with a lambda function (for value transformations). Last but not least: you can use .fillna('bla') to rapidly fill up NA values.

Answer from Carst on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-float-object-has-no-attribute
AttributeError: 'float' object has no attribute 'X' (Python) | bobbyhadz
The Python AttributeError: 'float' object has no attribute occurs when we try to access an attribute that doesn't exist on a floating-point number.
🌐
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'

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)
🌐
NBShare
nbshare.io › notebook › 242294077 › How-To-Solve-Error-Numpy-Has-No-Attribute-Float-In-Python
How To Solve Error Numpy Has No Attribute Float In Python
To solve this error, you will need to correct any typos in your code and make sure that you are using the correct attribute or method of the numpy module. ... import numpy as np # Correct way to create a float32 array array = np.array([1, 2, 3], dtype='float32') # Correct way to create a float ...
Find elsewhere
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 46018123 › attributeerror-float-object-has-no-attribute-get-coords
python 3.x - AttributeError: 'float' object has no attribute 'get_coords' - Stack Overflow
September 2, 2017 - I'm using Python 3.6.2, lecture example runs on Python 2.x. Whats the proper way to set values of x and y in function ans_quest? ... Can this method be called like this? This was the example in the lecture. ... import math, random, pylab, copy class Location(object): def __init__(self, x, y): self.x = float(x) self.y = float(y) def move(self, xc, yc): return Location(self.x+float(xc), self.y+float(yc)) def get_coords(self): return self.x, self.y def get_dist(self, other): ox, oy = other.get_coords() x_dist = self.x - ox y_dist = self.y - oy return math.sqrt(x_dist**2 + y_dist**2) class Compass
🌐
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
🌐
GitHub
github.com › teese › eccpy › issues › 16
'float' object has no attribute 'max' · Issue #16 · teese/eccpy
June 27, 2021 - Running your program on your test file generated_data_0.xlsx (Mac OS Big Sur, python 3.8.5) and get the following message: 'float' object has no attribute 'max' Here are details: AttributeError Traceback (most recent call last) in 1 settings = "/Users/nomadkml/Desktop/result/ECCpy_settings_template.xlsx" ----> 2 eccpy.run_curvefit(settings) 3 eccpy.run_gatherer(settings) ~/opt/anaconda3/lib/python3.8/site-packages/eccpy/curvefit.py in run_curvefit(settings_excel_file) 77 print("Starting run_curvefit program for selected samples.\n") 78 for fn in dff.loc[dff["run curvefit"] == True].index: ---> 79 calc_EC50(fn, dff, settings, t20) 80 else: 81 print("None of the datafiles are marked TRUE for 'run curvefit'.
Author   nomadkml
Top answer
1 of 9
65

The answer is already provided in the comments by @mattdmo and @tdelaney:

  • NumPy 1.20 (release notes) deprecated numpy.float, numpy.int, and similar aliases, causing them to issue a deprecation warning

  • NumPy 1.24 (release notes) removed these aliases altogether, causing an error when they are used

In many cases you can simply replace the deprecated NumPy types by the equivalent Python built-in type, e.g., numpy.float becomes a "plain" Python float.

For detailed guidelines on how to deal with various deprecated types, have a closer look at the table and guideline in the release notes for 1.20:

...

To give a clear guideline for the vast majority of cases, for the types bool, object, str (and unicode) using the plain version is shorter and clear, and generally a good replacement. For float and complex you can use float64 and complex128 if you wish to be more explicit about the precision.

For np.int a direct replacement with np.int_ or int is also good and will not change behavior, but the precision will continue to depend on the computer and operating system. If you want to be more explicit and review the current use, you have the following alternatives:

  • np.int64 or np.int32 to specify the precision exactly. This ensures that results cannot depend on the computer or operating system.
  • np.int_ or int (the default), but be aware that it depends on the computer and operating system.
  • The C types: np.cint (int), np.int_ (long), np.longlong.
  • np.intp which is 32bit on 32bit machines 64bit on 64bit machines. This can be the best type to use for indexing.

...

If you have dependencies that use the deprecated types, a quick workaround would be to roll back your NumPy version to 1.24 or less (as suggested in some of the other answers), while waiting for the dependency to catch up. Alternatively, you could create a patch yourself and open a pull request, or monkey patch the dependency in your own code.

2 of 9
39

In the 1.24 version:

The deprecation for the aliases np.object, np.bool, np.float, np.complex, np.str, and np.int is expired (introduces NumPy 1.20). Some of these will now give a FutureWarning in addition to raising an error since they will be mapped to the NumPy scalars in the future.

pip install "numpy<1.24" to work around it.

In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.23.5'

In [3]: np.float(3)
<ipython-input-3-8262e04d58e1>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
  np.float(3)
Out[3]: 3.0