numpy.ma.indices#
- ma.indices(dimensions, dtype=<class 'int'>, sparse=False) = <numpy.ma.core._convert2ma object>#
傳回代表網格索引的陣列。
計算一個陣列,其中的子陣列包含索引值 0, 1, …,且僅沿著對應軸變化。
- 參數:
- dimensions整數序列
網格的形狀。
- dtypedtype,選項性
結果的資料型別。
- sparse布林值,選項性
傳回網格的稀疏表示法,而非密集表示法。預設值為 False。
- 傳回值:
- grid一個 MaskedArray 或 MaskedArray 元組
- 如果 sparse 為 False
傳回一個網格索引陣列,
grid.shape = (len(dimensions),) + tuple(dimensions)
。- 如果 sparse 為 True
傳回陣列元組,其中
grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)
,且 dimensions[i] 位於第 i 個位置
註解
在密集情況下,輸出形狀是透過將維度數量前置於維度元組之前而獲得的,亦即,如果 dimensions 是長度為
N
的元組(r0, ..., rN-1)
,則輸出形狀為(N, r0, ..., rN-1)
。子陣列
grid[k]
包含沿著第k
軸的 N 維索引陣列。明確地說grid[k, i0, i1, ..., iN-1] = ik
範例
>>> import numpy as np >>> grid = np.indices((2, 3)) >>> grid.shape (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]])
索引可以用作陣列的索引。
>>> x = np.arange(20).reshape(5, 4) >>> row, col = np.indices((2, 3)) >>> x[row, col] array([[0, 1, 2], [4, 5, 6]])
請注意,在上述範例中,更直接的方式是使用
x[:2, :3]
直接提取所需的元素。如果 sparse 設定為 true,則網格將以稀疏表示法傳回。
>>> i, j = np.indices((2, 3), sparse=True) >>> i.shape (2, 1) >>> j.shape (1, 3) >>> i # row indices array([[0], [1]]) >>> j # column indices array([[0, 1, 2]])