[英]How to extract the upper values from the whole 3D array in python
是否可以從整個 3D 數組中提取上限值? 下面是一個 3D 陣列的簡單示例:
import numpy as np
a = np.array([[[7, 4, 2], [5, 0, 4], [0, 0, 5]],
[[7, 6, 1], [3, 9, 5], [0, 8, 7]],
[[8, 10, 3], [1, 2, 15], [9, 0, 1]]])
您可以使用 numpy 構建矩陣函數,例如numpy.triu (上三角)或numpy.tril (下三角)的對角矩陣的第 k 個副本,以返回對角矩陣上方或下方的第 k 個副本。
另一方面,如果您只對對角線上方或下方的值感興趣(沒有矩陣的副本),您可以簡單地使用numpy.triu_indices和numpy.tril_indices ,如下所示:
upper_index = np.triu_indices(n=3, k=1)
其中n
是返回索引有效的 arrays 的大小, k
是對角線偏移量。
並返回三角形的索引。 返回的元組包含兩個 arrays,每個都有沿着數組一維的索引:
(array([0, 0, 1], dtype=int64), array([1, 2, 2], dtype=int64))
現在您可以使用獲得的索引作為數組的索引,您將獲得:
a[upper_index]
並給出:
array([[5, 0, 4],
[0, 0, 5],
[0, 8, 7]])
同樣,您可以使用numpy.tril_indices
找到對角線下方的部分。
IUUC,您可以使用triu_indices :
result = a[np.triu_indices(3)]
print(result)
Output
[[7 4 2]
[5 0 4]
[0 0 5]
[3 9 5]
[0 8 7]
[9 0 1]]
如果你想要那些嚴格高於對角線的,你可以傳遞一個偏移值:
result = a[np.triu_indices(3, 1)]
print(result)
Output
[[5 0 4]
[0 0 5]
[0 8 7]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.