numpy三维切片、索引和省略号是如何工作的?

2024-03-28 19:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解numpy的一些切片和索引是如何工作的

第一个如下:

>>> x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
>>> x.shape
(2, 3, 1)
>>> x[1:2]
array([[[4],
        [5],
        [6]]])

根据documentation

If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.

那么这是否意味着[[1], [2], [3]] , [[4], [5], [6]]本身就是一个2x3数组?你知道吗

你怎么知道的

x[1:2]

返回

array([[[4],
        [5],
        [6]]])

什么?你知道吗

第二个是省略号

>>> x[...,0]
array([[1, 2, 3],
       [4, 5, 6]])

Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim. There may only be a single ellipsis present.

为什么[...,0]意味着什么?你知道吗


Tags: ofthetonumpynumberifobjectsis
1条回答
网友
1楼 · 发布于 2024-03-28 19:08:33

对于第一个问题,它意味着形状(2,3,1)的x有2片3x1数组。你知道吗

In [40]: x
Out[40]: 
array([[[1],
        [2],          # <= slice 1 of shape 3x1
        [3]],

       [[4],
        [5],          # <= slice 2 of shape 3x1
        [6]]])

现在,当您执行x[1:2]时,它只将第一个片段交给您,而不包括第二个片段,因为在Python&NumPy中,它总是左包含右独占的(类似于半开区间,即[1,2])

In [42]: x[1:2]
Out[42]: 
array([[[4],
        [5],
        [6]]])

这就是为什么你要吃第一片。你知道吗

关于你的第二个问题

In [45]: x.ndim
Out[45]: 3

所以,当您使用省略号时,它只是将数组扩展到3的大小。你知道吗

In [47]: x[...,0]
Out[47]: 
array([[1, 2, 3],
       [4, 5, 6]])

上面的代码意味着,从数组x获取两个切片,并将其按行拉伸。你知道吗

但是如果你这样做

In [49]: x[0, ..., 0]
Out[49]: array([1, 2, 3])

在这里,您只需从x获取第一个切片,并将其按行拉伸。你知道吗

相关问题 更多 >