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

matrix = np.array([])
s = np.squeeze(matrix)
print type(s)
print s

matrix = []
print type(s)
print s

s = 1
print type(s)
print s
``````

You can use the `item()` function:

``````import numpy as np

matrix = np.array([[[]]])
print(matrix.item())
``````

Output

``````7
``````

Numpy has a function explicitly for this purpose: asscalar

``````>>> np.asscalar(np.array())
24
``````

This uses `item()` in the implementation.

I guess `asscalar` was added to more explicit about what’s going on.

You can index with the empty tuple after squeezing:

``````x = np.array([[]])
s = np.squeeze(x)  # or s = x.reshape(())
val = s[()]
print val, type(val)
``````

You can use `np.take`

``````np.take(matrix,0)
``````

Sample run –

``````In : matrix = np.array([])

In : np.take(matrix,0)
Out: 67

In : type(np.take(matrix,0))
Out: numpy.int64
``````

``````>>> float(np.array([[[]]]))
1.
``````

You can use the numpy.flatten() function to flatten the array to a one dimensional array.
For instance:

``````s = []
print(s)
>>>> 1
``````

or

``````a=[,]
print(a)
>>>> 1
print(a)
>>>> 2
``````