Suppose I have 1x1x1x1x... array and wish to convert it to scalar?
How do I do it?
squeeze
does not help.
import numpy as np
ma
>>> float(np.array([[[[1]]]]))
1.
You can use the item()
function:
import numpy as np
matrix = np.array([[[[7]]]])
print(matrix.item())
Output
7
You can index with the empty tuple after squeezing:
x = np.array([[[1]]])
s = np.squeeze(x) # or s = x.reshape(())
val = s[()]
print val, type(val)
Numpy has a function explicitly for this purpose: asscalar
>>> np.asscalar(np.array([24]))
24
This uses item()
in the implementation.
I guess asscalar
was added to more explicit about what's going on.
You can use np.take -
np.take(matrix,0)
Sample run -
In [15]: matrix = np.array([[67]])
In [16]: np.take(matrix,0)
Out[16]: 67
In [17]: type(np.take(matrix,0))
Out[17]: numpy.int64