美文网首页
Numpy 简单教程(五)Numpy中的高级索引

Numpy 简单教程(五)Numpy中的高级索引

作者: 超级超级小天才 | 来源:发表于2020-08-17 16:46 被阅读0次

更过的Numpy教程连载内容:https://www.jianshu.com/nb/47449944

Numpy中的高级索引

使用索引list进行索引

使用一个由对应索引值组成的list或者tuple(可以是多维的)作为索引放入中括号中。当list/tuple是多维的时候,要保证每一维大小一致,因为返回的数组是根据list的形状确定的。

>>> a = np.arange(12)**2
>>> i = np.array([1, 1, 3, 8, 5])
>>> a[i]
array([ 1,  1,  9, 64, 25])

>>> j = np.array([[3, 4], [9, 7]])
>>> a[j]
array([[ 9, 16],
        [81, 49]])

使用布尔值数组作为索引

使用一个与原数组形状相同的布尔值数组作为索引,数组中的每一个元素是True还是False决定了是否取出这个位置对应的元素:

>>> a = np.arange(12).reshape(3,4)
>>> b = a > 4

>>> b
array([[False, False, False, False],
        [False,  True,  True,  True],
        [ True,  True,  True,  True]])

>>> a[b]
array([ 5,  6,  7,  8,  9, 10, 11])

使用 ix_() 函数

ix_() 函数的作用是将不同的向量整理成可以做运算的向量的形式,比如我有三个不同大小的向量a、b、c,我想让a、b、c中的每一个元素都对应地计算 a+b*c,那么可以这样做:

>>> b = np.array([8,5,4])
>>> c = np.array([5,4,6,8,3])
>>> ax,bx,cx = np.ix_(a,b,c)

>>> ax
array([[[2]],

        [[3]],

        [[4]],

        [[5]]])

>>> bx
array([[[8],
        [5],
        [4]]])

>>> cx
array([[[5, 4, 6, 8, 3]]])

>>> ax.shape, bx.shape, cx.shape
((4, 1, 1), (1, 3, 1), (1, 1, 5))

>>> result = ax+bx*cx

>>> result
array([[[42, 34, 50, 66, 26],
        [27, 22, 32, 42, 17],
        [22, 18, 26, 34, 14]],

        [[43, 35, 51, 67, 27],
        [28, 23, 33, 43, 18],
        [23, 19, 27, 35, 15]],

        [[44, 36, 52, 68, 28],
        [29, 24, 34, 44, 19],
        [24, 20, 28, 36, 16]],

        [[45, 37, 53, 69, 29],
        [30, 25, 35, 45, 20],
        [25, 21, 29, 37, 17]]])

>>> result[3,2,4]
17

>>> a[3]+b[2]*c[4]
17

使用字符串做索引

https://numpy.org/devdocs/user/basics.rec.html#structured-arrays

相关文章

网友评论

      本文标题:Numpy 简单教程(五)Numpy中的高级索引

      本文链接:https://www.haomeiwen.com/subject/gvztjktx.html