可以给出不不止一维的索引

来源:互联网 发布:东方财富期货软件 编辑:程序博客网 时间:2024/04/29 19:19


我们也可以给出不不止一维的索引,每一维的索引数组必须有相同的形状。

>>> a = arange(12).reshape(3,4)>>> aarray([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11]])>>> i = array( [ [0,1],                        # indices for the first dim of a...              [1,2] ] )>>> j = array( [ [2,1],                        # indices for the second dim...              [3,3] ] )>>>>>> a[i,j]                                     # i and j must have equal shapearray([[ 2,  5],       [ 7, 11]])>>>>>> a[i,2]array([[ 2,  6],       [ 6, 10]])>>>>>> a[:,j]                                     # i.e., a[ : , j]array([[[ 2,  1],        [ 3,  3]],       [[ 6,  5],        [ 7,  7]],       [[10,  9],        [11, 11]]])

自然,我们可以把i和j放到序列中(比如说列表)然后通过list索引。

>>> l = [i,j]>>> a[l]                                       # equivalent to a[i,j]array([[ 2,  5],       [ 7, 11]])

然而,我们不能把i和j放在一个数组中,因为这个数组将被解释成索引a的第一维。

>>> s = array( [i,j] )>>> a[s]                                       # not what we want---------------------------------------------------------------------------IndexError                                Traceback (most recent call last) in ()----> 1 a[s]IndexError: index (3) out of range (0<=index<2) in dimension 0>>>>>> a[tuple(s)]                                # same as a[i,j]array([[ 2,  5],       [ 7, 11]])


>>> a = arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i = array( [ [0,1],                        # indices for the first dim of a
... [1,2] ] )
>>> a[i]
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]])
>>> i.shape
(2, 2)
>>> a[i].shape
(2, 2, 4)
>>> a.shape
(3, 4)
>>> j = array( [ [2,1],                        # indices for the second dim
... [3,3] ] )
>>> a[i,j]
array([[ 2,  5],
       [ 7, 11]])
>>> a[i,2]
array([[ 2,  6],
       [ 6, 10]])
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i
array([[0, 1],
       [1, 2]])
>>> j
array([[2, 1],
       [3, 3]])
>>> a[:,j]
array([[[ 2,  1],
        [ 3,  3]],

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

       [[10,  9],
        [11, 11]]])
>>> l = [i,j]
>>> l
[array([[0, 1],
       [1, 2]]), array([[2, 1],
       [3, 3]])]
>>> a[l]
array([[ 2,  5],
       [ 7, 11]])
>>>


0 0
原创粉丝点击