numpy - 数组索引

时间:2021-08-10 06:50:02

numpy 数组索引

一、单个元素索引

一维数组索引

>>> x = np.arange(10)
>>> x[2]
2
>>> x[-2]
8

二维数组索引

>>> x.shape = (2,5) # now x is 2-dimensional
>>> x[1,3]
8
>>> x[1,-1]
9

数组切片

>>> x = np.arange(10)
>>> x[2:5]
array([2, 3, 4])
>>> x[:-7]
array([0, 1, 2])
>>> x[1:7:2]
array([1, 3, 5])
>>> y = np.arange(35).reshape(5,7)
>>> y[1:5:2,::3]
array([[ 7, 10, 13],
[21, 24, 27]])

二、使用数组索引数组

例:产生一个一组数组,使用数组来索引出需要的元素。让数组[3,3,1,8]取出x中的第3,3,1,8的四个元素组成一个数组view

>>> x = np.arange(10,1,-1)
>>> x
array([10, 9, 8, 7, 6, 5, 4, 3, 2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])

当然,类似切片那样,Index也可以使用负数。但是索引值不能越界!

>>> x[np.array([3,3,-3,8])]
array([7, 7, 4, 2])

三、索引多维数组

例1:产生一个5X7的数组,选择0,2,4行,0,1,2列的数

>>> y = np.arange(35).reshape(5,7)
>>> y[np.array([0,2,4]), np.array([0,1,2])]
array([ 0, 15, 30])

例2:选取第0,2,4行,第1列的值

>>> y[np.array([0,2,4]), 1]
array([ 1, 15, 29])

例3:选取第0,2,4行的值

>>> y[np.array([0,2,4])]
array([[ 0, 1, 2, 3, 4, 5, 6],
[14, 15, 16, 17, 18, 19, 20],
[28, 29, 30, 31, 32, 33, 34]])

四、布尔值或掩码索引数组

例1

>>> y = np.arange(35)
>>> b = y>20
>>> y[b]
array([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34])

例2

>>> b[:,5] # use a 1-D boolean whose first dim agrees with the first dim of y
array([False, False, False, True, True], dtype=bool)
>>> y[b[:,5]]
array([[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34]])

例3

>>> x = np.arange(30).reshape(2,3,5)
>>> x
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])
>>> b = np.array([[True, True, False], [False, True, True]])
>>> x[b]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])

  

五、数组与切片的组合索引数组  

例1:产生一个5X7的数组,使用数组来索引第一个轴,使用切换来索引第二个轴

>>> y = np.arange(35).reshape(5,7)
>>> y[np.array([0,2,4]),1:3]
array([[ 1, 2],
[15, 16],
[29, 30]])

例2:切片与布尔类型索引

>>> y[b[:,5],1:3]
array([[22, 23],
[29, 30]])

  

六、Structural indexing tools

例1:使用np.newwaxis可以直接扩展维度

>>> y.shape
(5, 7)
>>> y[:,np.newaxis,:].shape
(5, 1, 7)

例2:这是利用了扩展维度与广播特性的矩阵相加。用5X1矩阵与1X5矩阵相加。

>>> x = np.arange(5)
>>> x[:,np.newaxis] + x[np.newaxis,:]
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])

例3:使用 ... 符号来表示其他维度

>>> z = np.arange(81).reshape(3,3,3,3)
>>> z[1,...,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])

这例子也相当于下面的代码实现

>>> z[1,:,:,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])

  

  

另有:https://docs.scipy.org/doc/numpy/user/quickstart.html#fancy-indexing-and-index-tricks