0

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?

3
  • 1
    But x is a 3x3 matrix. How would you convert that to a float? astype converts the elements of the matrix. Commented Sep 13, 2017 at 16:55
  • if i got a 1x1 'numpy.ndarray' , how can i convert it to float64? Commented Sep 13, 2017 at 17:00
  • see answer below. Commented Sep 13, 2017 at 17:00

1 Answer 1

1

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'>
Sign up to request clarification or add additional context in comments.

1 Comment

Probably worth adding that the Numpy way of doing this would be to use the inbuilt function item. Just doing : np.dot(b,a.T).item() would return 12, although if float is really desired, call np.float54 is more suited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.