Numpy中np.indices函数用法详解

该博客介绍了numpy的indices函数,它用于生成指定形状的序号网格,可用于数组的切片操作。密集分布的网格返回一个行号和列号一一对应的数组,而稀疏分布则分别返回行和列的序号数组。通过示例展示了如何使用这两个网格进行切片,等效于直接的切片操作x[:2,:3]。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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时返回的是一个行号和列号一一对应序号网格,这个序号网格可以用于实现数组的切片操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daimashiren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值