如何理解numpy的切片和索引组合示例 [英] How to understand numpy's combined slicing and indexing example

查看:90
本文介绍了如何理解numpy的切片和索引组合示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解numpy的切片和索引组合概念,但是我不确定如何从numpy的输出中正确获得以下结果(以便我们可以了解numpy的过程如何将切片和索引组合在一起,哪一个是首先处理?):

I am trying to understand numpy's combined slicing and indexing concept, however I am not sure how to correctly get the below results from numpy's output (by hand so that we can understand how numpy process combined slicing and indexing, which one will be process first?):

>>> import numpy as np
>>> a=np.arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i=np.array([[0,1],[2,2]])
>>> a[i,:]
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [ 8,  9, 10, 11]]])
>>> j=np.array([[2,1],[3,3]])
>>> a[:,j]
array([[[ 2,  1],
        [ 3,  3]],

       [[ 6,  5],
        [ 7,  7]],

       [[10,  9],
        [11, 11]]])
>>> aj=a[:,j]
>>> aj.shape
(3L, 2L, 2L)

我对上面输出的aj的形状如何变成(3,2,2)感到有些困惑,非常感谢任何详细的解释,谢谢!

I am bit confused about how aj's shape becomes (3,2,2) with the above output, any detailed explanations are very appreciated, thanks!

推荐答案

每当使用索引数组时,结果的形状与索引相同.例如:

Whenever you use an array of indices, the result has the same shape as the indices; for example:

>>> x = np.ones(5)
>>> i = np.array([[0, 1], [1, 0]])
>>> x[i]
array([[ 1.,  1.],
       [ 1.,  1.]])

我们用2x2数组建立了索引,结果是2x2数组.与切片组合时,将保留切片的大小.例如:

We've indexed with a 2x2 array, and the result is a 2x2 array. When combined with a slice, the size of the slice is preserved. For example:

>>> x = np.ones((5, 3))
>>> x[i, :].shape
(2, 2, 3)

第一个示例是2x2的项目数组,而本示例是2x2的(长度为3)行的数组.

Where the first example was a 2x2 array of items, this example is a 2x2 array of (length-3) rows.

切换切片的顺序时也是如此:

The same is true when you switch the order of the slice:

>>> x = np.ones((5, 3))
>>> x[:, i].shape
(5, 2, 2)

这可以看作是五个2x2数组的列表.

This can be thought of as a list of five 2x2 arrays.

请记住:使用列表或数组对任何维进行索引时,结果的形状是索引的形状,而不是输入的形状.

Just remember: when any dimension is indexed with a list or array, the result has the shape of the indices, not the shape of the input.

这篇关于如何理解numpy的切片和索引组合示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆