Error: ‘numpy.float64’ object cannot be interpreted as an integer
The range() function in Python is used to return a sequence of numbers that starts from 0 and increments by 1. It accepts only integers, not float values. If we try to pass the float values to this function, it will result in an error.
To demonstrate, create a numpy array named camp_budgets with five values and try to display the range of values at each index by iterating the array inside the for loop.
# Create numpy array with 5 values
camp_budgets = numpy.array([2000.00,4500.50,5000.60,2000.60,7000.90])
print(camp_budgets,"\n")
# Try to display range of values at each index
for i in range(len(camp_budgets)):
print(range(camp_budgets[i]))
Output
You can see that TypeError is encountered while converting float values in the range.
Solution 1: Using astype()
The astype() method is used for casting the given object to a specified data type. It takes the data type to be converted as the parameter. Here, we need to convert the float type to an integer (parameter – int). Let’s create the same array as above and display the range of values at each index by converting it into a range of values with the range() function.
# Create numpy array with 5 values
camp_budgets = numpy.array([2000.00,4500.50,5000.60,2000.60,7000.90])
print(camp_budgets,"\n")
# Display range of values at each index
for i in range(len(camp_budgets)):
print(range(camp_budgets.astype(int)[i]))
Output
We can see that the TypeError is fixed and a range of values are displayed.
Solution 2: Using int()
The int() function in Python is used to convert the given string or number into an integer. Here, the input is float. So, we need to pass the parameter as float to this function.
Let’s create the same array as above and display the range of values at each index by converting it into a range of values with the range() function. Typecase the iterator with int() by passing as a parameter to this function.
# Create numpy array with 5 values
camp_budgets = numpy.array([2000.00,4500.50,5000.60,2000.60,7000.90])
print(camp_budgets,"\n")
# Display range of values at each index
for i in range(len(camp_budgets)):
print(range(int(camp_budgets[i])))
Output
We can see that the TypeError is fixed and a range of values are displayed.
Conclusion
First, we reproduced the TypeError – ‘numpy.float64’ object cannot be interpreted as an integer by creating a numpy array with float values and converting it into a range of values. Next, we discovered two solutions that will convert float values to integers while creating the range, using the astype() and int() functions.