numpy.indices#
- numpy.indices(dimensions, dtype=<class 'int'>, sparse=False)[source]#
返回一個表示網格索引的陣列。
計算一個陣列,其中的子陣列包含索引值 0, 1, …,僅沿相應軸變化。
- 參數:
- dimensions整數序列
網格的形狀。
- dtypedtype,選用
結果的資料型別。
- sparse布林值,選用
返回網格的稀疏表示,而非稠密表示。預設值為 False。
- 返回:
- grid一個 ndarray 或 ndarray 元組
- 如果 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-th
軸的 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]])