How to Solve Python TypeError: ‘numpy.float64’ object cannot be interpreted as an integer

by | Programming, Python, Tips

If you try to pass a numpy.float64 object to a function or method that expects an integer, you will throw the TypeError: ‘numpy.float64’ object cannot be interpreted as an integer. You can convert the float64 objects to integers using the built-in int method to solve this error.

The type of parameters for the method you are trying to use may have also changed with a library update, in which case, check the library documentation.

This tutorial will go through the error in detail and how to solve it with code examples.


TypeError: ‘numpy.float64’ object cannot be interpreted as an integer

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “numpy.float64 object” tells us the error concerns an illegal operation for numpy.float64 data. The part “cannot be interpreted as an integer” tells us the operation we are using expects an integer and instead receives a numpy.float64.

Example #1: Creating a NumPy array Using ndarray

Let’s look at an example where we have a list of numerical strings. We want to convert the strings to numpy.float64 and then convert the list to a NumPy array using the ndarray() method. Let’s look at the code:

vals = ['-0.782', '0.561', '0.895']

float_vals = [np.float64(x) for x in vals]

arr = np.ndarray(float_vals)

print(arr)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [45], in <cell line: 3>()
      1 vals = ['-0.782', '0.561', '0.895']
      2 float_vals = [np.float64(x) for x in vals]
----> 3 arr = np.ndarray(float_vals)
      4 print(arr)

TypeError: 'numpy.float64' object cannot be interpreted as an integer

The TypeError occurs because the first argument of the ndarray() method is shape, which is a tuple of integers. In this case, we pass numpy.float64 to the ndarray method, which is an incorrect type.

Solution

We should not use the ndarray constructor method to create arrays. We can use the numpy.array() method to take the numerical strings directly without converting them to float64. We can specify the type of elements in the array using the dtype parameter. Let’s look at the revised code

import numpy as np

vals = ['-0.782', '0.561', '0.895']

arr = np.array(vals, dtype=np.float64)

print(arr)

Let’s run the code to get the result:

[-0.782  0.561  0.895]

We successfully convert the list of numerical strings to a NumPy array of floats.

Example #2: Using Range with numpy.float64 values

Let’s look at a second example where we want to iterate over an array of floating-point numbers. We will iterate over the preceding numbers for each floating-point number and calculate the modulo of the floating-point number and the preceding numbers.

import numpy as np
#define array of values
data = np.array([3.0, 4.0, 5.0, 7.0, 10.0, 11.0])

#use for loop to iterate over values
for i in range(len(data)):
#use for loop to iterate over preceding numbers
    for j in range(data[i]):
#If number is greater than zero calculate modulo
        if j > 0:
#Print remainder to console
            print(f'{data[i]} % {j} = {round(data[i] %j, 0)}')

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [64], in <cell line: 6>()
      5 #use for loop to iterate over values
      6 for i in range(len(data)):
      7 #use for loop to iterate over preceding numbers
----> 8     for j in range(data[i]):
      9 #If number is greater than zero calculate modulo
     10         if j > 0:
     11 #Print remainder to console
     12             print(round(data[i] %j, 0))

The error occurs because, in the second loop, we call the range() method with a floating-point number parameter value (data[i]). The range() method only accepts integers for its parameter values.

Solution

To solve this error, we can convert the floating-point number to an integer using the built-in int() method. Let’s look at the revised code:

import numpy as np
#define array of values
data = np.array([3.0, 4.0, 5.0, 7.0, 10.0, 11.0])

#use for loop to iterate over values
for i in range(len(data)):
#use for loop to iterate over preceding numbers
    for j in range(int(data[i])):
#If number is greater than zero calculate modulo
        if j > 0:
#Print remainder to console
            print(f'{data[i]} % {j} = {round(data[i] %j, 0)}')

Let’s run the code to get the result:

3.0 % 1 = 0.0
3.0 % 2 = 1.0
4.0 % 1 = 0.0
4.0 % 2 = 0.0
4.0 % 3 = 1.0
5.0 % 1 = 0.0
5.0 % 2 = 1.0
5.0 % 3 = 2.0
5.0 % 4 = 1.0
7.0 % 1 = 0.0
7.0 % 2 = 1.0
7.0 % 3 = 1.0
7.0 % 4 = 3.0
7.0 % 5 = 2.0
7.0 % 6 = 1.0
10.0 % 1 = 0.0
10.0 % 2 = 0.0
10.0 % 3 = 1.0
10.0 % 4 = 2.0
10.0 % 5 = 0.0
10.0 % 6 = 4.0
10.0 % 7 = 3.0
10.0 % 8 = 2.0
10.0 % 9 = 1.0
11.0 % 1 = 0.0
11.0 % 2 = 1.0
11.0 % 3 = 2.0
11.0 % 4 = 3.0
11.0 % 5 = 1.0
11.0 % 6 = 5.0
11.0 % 7 = 4.0
11.0 % 8 = 3.0
11.0 % 9 = 2.0
11.0 % 10 = 1.0

We successfully printed the division remainder for each number in the array by the preceding numbers.

Summary

Congratulations on reading to the end of this tutorial! The error “TypeError: ‘numpy.float64’ object cannot be interpreted as an integer” occurs when you try to use a method or function that expects an integer but receives a numpy.float64 instead. The easiest way to resolve this error is to convert the values to integers using the built-in int() method.

For further reading on TypeErrors involving NumPy, go to the article: How to Solve Python TypeError: cannot perform reduce with flexible type.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee