numpy.indices#
- numpy.indices(dimensions, dtype=<class 'int'>, sparse=False)[源代码]#
返回表示网格索引的数组.
计算一个数组,其中子数组包含索引值 0, 1, … 仅沿相应的轴变化.
- 参数:
- 维数整数序列
网格的形状.
- dtypedtype, optional
结果的数据类型.
- 稀疏布尔值,可选
返回网格的稀疏表示,而不是密集表示.默认为 False.
- 返回:
- 网格一个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-D 索引数组.显式表示为: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]])