np.indices官方文档定义如下:
def indices(dimensions, dtype=int, sparse=False):
"""
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0, 1, ...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : dtype, optional
Data type of the result.
sparse : boolean, optional
Return a sparse representation of the grid instead of a dense
representation. Default is False.
.. versionadded:: 1.17
Returns
-------
grid : one ndarray or tuple of ndarrays
If sparse is False:
Returns one array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
If sparse is True:
Returns a tuple of arrays, with
``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
dimensions[i] in the ith place
官方文档中的描述较为抽象,简单来说。np.indices的作用就是返回一个给定形状数组的序号网格数组,可以用于提取数组元素或对数组进行切片使用。请看下面的例子:
实例:
import numpy as np
x = np.arange(20).reshape((5,4))
dense_grid = np.indices((2,3)) #返回一个2x3网格序列,密集分布,每个行号和列号一一对应,表示一个位置的元素。
sparse_grid = np.indices((2,3),sparse= True) #返回一个松散排布的2x3网格的行分布和列分布元组,行号和列号不是一一对应,一个行号对应多个列号。
print("x:\n",x)
print("x.shape:",x.shape)
print("================================")
print("dense_grid:\n",dense_grid)
print("================================")
print("行序号:\n",dense_grid[0])
print()
print("列序号:\n ",dense_grid[1])
print("\n")
print("切片效果:\n", x[dense_grid[0],dense_grid[1]]) #等效于x[:2,:3]切片效果
print("================================")
print("sparse_grid:\n",sparse_grid)
print("================================")
print("切片效果: \n",x[sparse_grid]) #等效于x[:2,:3]切片效果
运行结果:
x:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
x.shape: (5, 4)
================================
dense_grid: #密集分布,行号和列号一一对应,例如(0,0)位置表示元素0,(1,0)位置表示元素4,以此类推。
[[[0 0 0]
[1 1 1]]
[[0 1 2]
[0 1 2]]]
================================
行序号:
[[0 0 0]
[1 1 1]]
列序号:
[[0 1 2]
[0 1 2]]
切片效果: #利用密集网格实现了对原数组两行三列的一个子数组的截取,等效于x[:2,:3]
[[0 1 2]
[4 5 6]]
================================
sparse_grid: #松散分布,元组的第一个参数表示行号,第二个参数表示列号。
(array([[0],
[1]]), array([[0, 1, 2]]))
================================
切片效果: #利用松散网格实现了对原数组两行三列的一个子数组的截取,等效于x[:2,:3]
[[0 1 2]
[4 5 6]]
总结: np.indices((2,3),sparse= True)返回一个2x3形状的数组的序号网格,设定spare=True时返回的是一个松散分布的行分布和列分布的元组,相反spare=False时返回的是一个行号和列号一一对应序号网格,这个序号网格可以用于实现数组的切片操作。