You can use the item() function:
import numpy as np
matrix = np.array([[[[7]]]])
print(matrix.item())
Output
7
Answer from gtlambert on Stack OverflowYou can use the item() function:
import numpy as np
matrix = np.array([[[[7]]]])
print(matrix.item())
Output
7
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.
Update:
As of 2023 this function has been removed from NumPy (see v1.23 release notes).
python - Numpy convert scalars to arrays - Stack Overflow
python - How to convert neatly 1 size numpy array to a scalar? Numpy "asscalar" gives error when input is not a 1 size array. - Stack Overflow
What are numpy scalars used for?
Convert 1*1 matrix/array to scalar
See atleast_1d:
Convert inputs to arrays with at least one dimension.
>>> import numpy as np
>>> x = 42 # x is a scalar
>>> np.atleast_1d(x)
array([42])
>>> x_is_array = np.array(42) # A zero dim array
>>> np.atleast_1d(x_is_array)
array([42])
>>> x_is_another_array = np.array([42]) # A 1d array
>>> np.atleast_1d(x_is_another_array)
array([42])
>>> np.atleast_1d(np.ones((3, 3))) # Any other numpy array
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
When I'm unsure whether x will be a scalar, list/tuple or array, I've been using:
x = np.asarray(x).reshape(1, -1)[0,:]
Alternatively by (ab)using the broadcasting rules, you could equally write:
x = np.asarray(x) * np.ones(1)
Perhaps a slightly more streamlined syntax is to make use of the extra arguments on the array constructor:
x = np.array(x, ndmin=1, copy=False)
Which will ensure that the array has at least one dimension.
But this is one of those things that seems a bit clumsy in numpy
Am I correct in treating scalars as souped-up versions of 'standard' Python data types (+ some new data types not in base Python), which happen to have the same attributes and methods that ndarrays have, even though many of such attributes/methods are meaningless to scalars?
The one part that confuses me a lot on the document is the term "array scalars". What does the word array have to do with the scalar?
https://numpy.org/doc/stable/reference/arrays.scalars.html