freefrog
freefrog

Reputation: 705

Convert 'numpy.ndarray' to float64 failed in python?

This is my code below:

a = np.array([[1,2,3]])
b = np.array([[2,2,2]])
x = np.dot(b,a.T)
print(type(x))

This give me 'numpy.ndarray',I want to convert 'numpy.ndarray' to float64:

x = x.astype(np.float64)
print(type(x))

but it returned 'numpy.ndarray', why doesn't work?

Upvotes: 0

Views: 3215

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

Short answer: you probably want to use float(np.dot(a,b.T)).

Your np.dot generates a 3×3 matrix:

>>> np.dot(a.T,b)
array([[2, 2, 2],
       [4, 4, 4],
       [6, 6, 6]])

And there is no universal inherent way to convert a matrix to a float (you can of course calculate for instance the determinant, but that is a conversion).

You probably want to use the np.dot the other way around:

>>> np.dot(a,b.T)
array([[12]])

Now it is a 1×1 matrix. Here it is of course reasonable to simply pop the element out of the matrix. We can do this through indexing:

>>> np.dot(a,b.T)[0,0]
12
>>> type(np.dot(a,b.T)[0,0])
<class 'numpy.int64'>

So now we obtained the single in64 element. This is still not a float, but now we can use the float constructor of Python to obtain a float:

>>> float(np.dot(a,b.T)[0,0])
12.0
>>> type(float(np.dot(a,b.T)[0,0]))
<class 'float'>

Now the best part is that in case the matrix contains only a single element, numpy makes it more convenient, and you can simply call float(..) on the matrix. So:

>>> float(np.dot(a,b.T))
12.0

In case you want to use a np.float64, it is more or less the same:

>>> np.float64(np.dot(a,b.T))
12.0
>>> type(np.float64(np.dot(a,b.T)))
<class 'numpy.float64'>

Upvotes: 1

Related Questions