numpy.indices

numpy.indices(dimensions, dtype=<class 'int'>, sparse=False)[源代码]

返回表示网格索引的数组。

计算一个数组,其中子数组包含索引值0,1。。。仅沿相应轴变化。

参数
dimensions整数序列

网格的形状。

dtype可选类型

结果的数据类型。

sparse布尔值,可选

返回网格的稀疏表示,而不是密集表示。默认值为False。

1.17 新版功能.

返回
grid一个数组或数组的元组
如果sparse为False:

返回一个网格索引数组, grid.shape = (len(dimensions),) + tuple(dimensions) .

如果稀疏为真:

返回数组的元组,其中 grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) 带尺寸 [i] 在第i个地方

参见

mgrid, ogrid, meshgrid

笔记

稠密情况下的输出形状是通过在维数元组前面加上维数来获得的,即如果 dimensions 是元组 (r0, ..., rN-1) 长度的 N ,输出形状为 (N, r0, ..., rN-1) .

子阵列 grid[k] 包含沿 k-th 轴。明确地::

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]])