'numpy.float64' object cannot be interpreted as an integer in Python

Dung Do Tien May 03 2022 24

Hi Guys, I have two arrays that contain names and scores of subjects and I want to print out of them one by one, like this:

import numpy as np

subjects = np.array(["Math", "physics", "literature", "Chemistry", "history"])
subject_point = np.array([5.5, 8, 9.5, 7, 6])

for i in range(len(subjects)):
    print(subjects[i])
    print(range(subject_point[i]))

But When I was running the code above and got an exception TypeError: 'numpy.float64' object cannot be interpreted as an integer

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(range(subject_point[i]))
TypeError: 'numpy.float64' object cannot be interpreted as an integer

It really worked for me. Anyone can help me explain it?

I'm using Python 3.9 and Windows 11.

Thanks in Advance.

Have 1 answer(s) found.
  • J

    Javier Vidal May 03 2022

    This error occurred because the range() function only accepts an integer number but you passed a float number. We have 2 ways to solve your problem:

    1. Using int() method help convert float to int number

    import numpy as np
    
    subjects = np.array(["Math", "physics", "literature", "Chemistry", "history"])
    subject_point = np.array([5.5, 8, 9.5, 7, 6])
    
    for i in range(len(subjects)):
        print(subjects[i])
        print(range(int(subject_point[i])))

    #Output

    Math
    range(0, 5)
    physics
    range(0, 8)
    literature
    range(0, 9)
    Chemistry
    range(0, 7)
    history
    range(0, 6)

    2. Don't use range() method when printing out the value

    import numpy as np
    
    subjects = np.array(["Math", "physics", "literature", "Chemistry", "history"])
    subject_point = np.array([5.5, 8, 9.5, 7, 6])
    
    for i in range(len(subjects)):
        print(subjects[i])
        print(subject_point[i])

    #Output

    Math
    5.5
    physics
    8.0
    literature
    9.5
    Chemistry
    7.0
    history
    6.0

    Hope this answer is useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close