Only size 1 arrays can be converted to python scalars

Stark Wayne picture Stark Wayne · Jan 15, 2018 · Viewed 10.7k times · Source

I created a 3 dimensional object using numpy.random module such as

import numpy as np
b = np.random.randn(4,4,3)

Why can't we cast type float to b?

TypeError

actual code

Answer

hyper-neutrino picture hyper-neutrino · Jan 15, 2018

You can't float(b) because b isn't a number, it's a multidimensional array/matrix. If you're trying to convert every element to a Python float, that's a bad idea because numpy numbers are more precise, but if you really want to do that for whatever reason, you can do b.tolist(), which returns a Python list of floats. However, I don't believe you can have a numpy matrix of native Python types because that doesn't make any sense.