[英]How to convert singleton array to a scalar value in Python?
假設我有 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
您可以使用item()
函數:
import numpy as np
matrix = np.array([[[[7]]]])
print(matrix.item())
輸出
7
您可以在壓縮后使用空元組進行索引:
x = np.array([[[1]]])
s = np.squeeze(x) # or s = x.reshape(())
val = s[()]
print val, type(val)
您可以使用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
>>> float(np.array([[[[1]]]]))
1.
您可以使用 numpy.flatten() 函數將數組展平為一維數組。 例如:
s = [[1]]
print(s[0][0])
>>>> 1
或者
a=[[1],[2]]
print(a[0][0])
>>>> 1
print(a[1][0])
>>>> 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.