簡體   English   中英

如何在 Python 中將單例數組轉換為標量值?

[英]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

Numpy 有一個明確用於此目的的函數: asscalar

>>> np.asscalar(np.array([24]))
24

這在實現中使用item()

我猜添加了asscalar以更明確地說明正在發生的事情。

您可以在壓縮后使用空元組進行索引:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM