numpy索引问题
numpy索引问题
1.传入为一个元素时
切片。
import numpy as np
a = np.arange(12).reshape(3,4)
>>>a[1:,2:]
array([[ 6, 7],
[10, 11]])
数组。当查询数组是1维时,传入的索引是数组形状时,取出的值是与传入的数组形状相同
b = np.arange(12)**2
i = np.array([1, 1, 3, 8, 5]) # an array of indices
>>>b[i]
array([ 1, 1, 9, 64, 25])
j = np.array([[3, 4], [9, 7]]) # a bidimensional array of indices
>>>b[j]
array([[ 9, 16],
[81, 49]])
当查询矩阵是二维时
palette = np.array([[0, 0, 0], # black
[255, 0, 0], # red
[0, 255, 0], # green
[0, 0, 255], # blue
[255, 255, 255]]) # white
image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette
[0, 3, 4, 0]])
palette[image] # the (2, 4, 3) color image
array([[[ 0, 0, 0],
[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[ 0, 0, 255],
[255, 255, 255],
[ 0, 0, 0]]])
综上,设有个查询数组a,对传入的索引数组ind,进行以下操作
for i in ind:
a[i]
例如,对image进行遍历,第一个元素是[0,1,2,0],a的第0个元素是[0,0,0],第1个元素是[255,0,0],以此类推。
第二个元素是[0,3,4,0],按照同样的道理取出a的第0,3,4,0个元素。
2.传入两个元素时
对于传入两个元素均为多维数组时,
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], # indices for the first dim of `a`
[1, 2]])
j = np.array([[2, 1], # indices for the second dim
[3, 3]])
>>>a[i, j] # i和j必须相同shape。
array([[ 2, 5],
[ 7, 11]])
>>>a[i, 2]
array([[ 2, 6],
[ 6, 10]])
当传入如上形式的索引时,其中,i是第一维度索引,j是第二维度索引,二者要匹配,然后根据匹配的(i,j)查出对应位置元素,放置该位置。
>>>a[:, j]
array([[[ 2, 1],
[ 3, 3]],
[[ 6, 5],
[ 7, 7]],
[[10, 9],
[11, 11]]])
当仅往列坐标位置传入数组时,查询方式为,对每一行按照j的索引位置查询列值。
具体原理与上文方式类似。但当传入列参数时,取出的就不是第一个元素了,需要加入列元素。例如,a[i,j],对i进行遍历,第一个元素是[0,1],a[[0,1]]==[[0,1,2,3],[4,5,6,7]],再根据对应的列元素[2,1],分别取出第一个的2位置元素,和第二个的1位置元素,[2,5]
浙公网安备 33010602011771号