How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer
In this article, we are going to see how to fix: ‘numpy.float64’ object cannot be interpreted as an integer.
When a function or operation is applied to an object of the wrong type, a type error is raised. The ‘numpy.float64’ object cannot be interpreted as an integer is one example of this type of problem. Let’s see what we can do about that.
When do we get ‘‘numpy.float64’ object cannot be interpreted as an integer ‘?
if we give a float number in a range() in python, it results in a ”numpy.float64’ object that cannot be interpreted as an integer ‘ error.
range() function: The range() function returns a number series that starts at 0 and increments by 1 before stopping at a specified value.
syntax: range(start,stop,step)
Python3
# code import numpy as np # an array of float values arr = np.array([ 1.5 , 2.5 , 3.5 ]) # we loop to print out range of values # at each index for i in range ( len (arr)): print ( range (arr[i])) |
Output:
TypeError: ‘numpy.float64’ object cannot be interpreted as an integer
How to fix this error?
when we have a list of values, and we want to change their type to prevent errors.
Method 1: Using astype()
We can use the .astype() function and give the argument “int”. astype() function: When we need to convert a certain array of data from one type to another, the method comes in helpful.
Parameters
- dtype: refers to data type of list, or dict of column name
- copy: boolean value,in default it’s set to True
- errors: {‘raise’, ‘ignore’}, default is ‘raise’
Python3
# code import numpy as np # an array of float values arr = np.array([ 1.5 , 2.5 , 3.5 ]) arr = arr.astype( int ) # we loop to print out range of values # at each index for i in range ( len (arr)): print ( range (arr[i])) |
Output:
range(0, 1) range(0, 2) range(0, 3)
Method 2: Using Int() function
Here we will int() function to cast the array object before getting into range.
Python3
# code import numpy as np # an array of float values arr = np.array([ 1.5 , 2.5 , 3.5 ]) # we loop to print out range of values # at each index for i in range ( len (arr)): print ( range ( int (arr[i]))) |
Output:
range(0, 1) range(0, 2) range(0, 3)