How to convert singleton array to a scalar value in Python?

ぐ巨炮叔叔 提交于 2019-12-30 05:47:38

问题


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([[1]])
s = np.squeeze(matrix)
print type(s)
print s

matrix = [[1]]
print type(s)
print s

s = 1
print type(s)
print s

回答1:


You can use the item() function:

import numpy as np

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

Output

7



回答2:


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.




回答3:


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)



回答4:


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


来源:https://stackoverflow.com/questions/35157742/how-to-convert-singleton-array-to-a-scalar-value-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!