numpy数组索引数组

在看Aligned代码的时候发现里面有numpy数组里数组索引数组,于是做了这个实验
>>> import numpy as np

>>> a=np.array([0,1,2])
>>> b=np.array([0,1,2,3])
>>> c=np.array([[0,1,2],[1,0,2],[2,1,0]])

>>> d=(b[c]==a[:,np.newaxis])[3,3]结构与[,3]结构相比较,出来的结果是[3,3]结构的布尔matrix
>>> d结果出来的是补齐再进行==运算
array([[ True, False, False],
       [ True, False, False],
       [ True, False, False]])
>>> a[:,np.newaxis]
array([[0],
       [1],
       [2]])


>>> b[c]           出来结果和c相同,b为[4,]结构,c为[3,3]结构,b[c]为[3,3]结构
array([[0, 1, 2],结果出来的是与b[c]=c
       [1, 0, 2],
       [2, 1, 0]])

>>> a1=np.array([[55,66,77],[11,22,33]])再来感受一下
>>> b1=np.array([[1,2,3,4],[2,3,4,5]])
>>> a1[b1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2
>>> b1[a1]

>>> a2=np.array([[55,66,77],[11,22,33]])再来个实验,感受一下
>>> b2=np.array([[0,1],[1,0],[0,1],[1,0]])
>>> a2[b2]
array([[[55, 66, 77],这两行是b2中的第一行的[0,1]作为索引出来的结果,也就是a2[0,1]
        [11, 22, 33]],these two lines are the results of a2 indexed as [0,1], same as a2[b2[0]]

       [[11, 22, 33],
        [55, 66, 77]],

       [[55, 66, 77],
        [11, 22, 33]],

       [[11, 22, 33],
        [55, 66, 77]]])

猜你喜欢

转载自blog.csdn.net/ptgood/article/details/82907141