np.unravel_index(indices, shape, order = ‘C’) 一句话概括:求出数组某元素(或某组元素)拉成一维后的索引值在原本维度(或指定新维度)中对应的索引
官网给出的概括是convert a flat index or array of flat indices into a tuple of coordinate arrays.
- indices: 整数构成的数组, 其中元素是索引值(integer array whose elements are indices into flattened version of array)
- shape: tuple of ints, 一般是原本数组的维度,也可以给定的新维度。
A = np.random.randiant(1, 100, size = (2, 3, 5))
print(A)
array([[[98, 29, 32, 73, 90],
[36, 52, 24,2, 37],
[66, 80, 23, 29, 98]],[[17, 32, 58, 99, 74],
[53,3, 20, 48, 28],
[53,7, 74, 34, 68]]])
#利用argmax求最大值对应的索引
ind_max = np.argmax(A)
print(ind_max)
18
#由观察知, 18是矩阵A中99拉伸成一维之后的索引值, 接下来利用unravel_index求其在自身维度(2,3,5)下的索引值
ind_max_src = https://www.it610.com/article/np.unravel_index(ind_max, A.shape)
print(ind_max_src)
(1, 0, 3)
#验证此索引值对应的元素为99
print(A[ind_max_src])
99
index可以升维,假设取indices = (4, 7), 此时np.unravel_index输出的结果为3个数组(3即为A的维度),每个数组的第0位为下标为4的元素在A.shape下的下标, 每个数组的第1位为下标为7的元素在A.shape下的下标
inds = np.unravel_index((4, 7), A.shape)
print(inds)
(array([0, 0]), array([0, 1]), array([4, 2]))
#验证
first_ind = (inds[0][0], inds[1][0], inds[2][0])
Sec_ind = (inds[0][1], inds[1][1], inds[2][1])
print(A[first_ind], A[Sec_ind])
90, 24
练习: 100 Numpy Exercise (20)
构造一个维度为6x7x8的数组,并找出第100个元素的索引(x,y,z)
np.unravel_index(99, (6,7,8))