Python – The “numpy.float64” object cannot be interpreted as an integer

The “numpy.float64” object cannot be interpreted as an integer… here is a solution to the problem.

The “numpy.float64” object cannot be interpreted as an integer

Here is the code in question :

arr = ['-0.944', '0.472', '0.472']
charges = [np.float64(i) for i in arr] # [-0.944, 0.472, 0.472]
charges = np.ndarray(charges)

The error is thrown at the last step, at which point the list is converted to an ndarray. Assigning dtype=np.float64 in ndarray does not change the error. What’s wrong with this code?

NumPy 1.14,
Python 3.6.1

Solution

The first argument to np.ndarray is shape, which is usually an integer tuple.

You should not use the low-level constructor np.ndarray. The correct interface is np.array, get it directly from the string without first doing list comprehension:

>>> arr = ['-0.944', '0.472', '0.472']
>>> np.array(arr, dtype=np.float64)
array([-0.944,  0.472,  0.472])

Related Problems and Solutions