NumPy参考 >例行程序 >Indexing routines > numpy.indices
numpy.
indices
(Dimensions,dtype = <class'int'>,sparse = False )[源代码] ¶返回表示网格索引的数组。
计算一个数组,其中子数组包含仅沿相应轴变化的索引值0、1,…。
网格的形状。
结果的数据类型。
返回网格的稀疏表示,而不是密集表示。默认值为False。
1.17版中的新功能。
返回一个网格索引数组
。grid.shape = (len(dimensions),) + tuple(dimensions)
返回数组的元组,
第[i]个维的位置grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)
笔记
在稠密情况下,输出形状是通过在维数元组前面添加维数而获得的,即,如果维数
是长度的元组,则输出形状为
。(r0, ..., rN-1)
N
(N, r0, ..., rN-1)
子grid[k]
数组包含沿k-th
轴的索引的ND数组
。明确地:
grid[k, i0, i1, ..., iN-1] = ik
例子
>>> 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]])