如何在Python中将单例数组转换为标量值?

时间:2016-02-02 15:43:00

标签: python numpy multidimensional-array

假设我有1x1x1x1x ...数组并希望将其转换为标量?

我该怎么做?

squeeze没有帮助。

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

6 个答案:

答案 0 :(得分:19)

您可以使用item()功能:

import numpy as np

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

<强>输出

7

答案 1 :(得分:9)

Numpy为此目的明确提供了一项功能:asscalar

found

这会在implementation中使用>>> np.asscalar(np.array([24])) 24

我想item()更加明确地说明了发生了什么。

答案 2 :(得分:6)

你可以在挤压后使用空元组进行索引:

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

答案 3 :(得分:1)

您可以使用np.take -

np.take(matrix,0)

示例运行 -

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

您可以使用 numpy.flatten() 函数将数组展平为一维数组。 例如:

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

a=[[1],[2]]
print(a[0][0])
>>>> 1
print(a[1][0])
>>>> 2
相关问题