- First look at the two-dimensional array
Suppose we want to get the position index of the largest two valuesa = np.array([[1, 7, 5], [8, 2, 13]])
- We first expand the two-dimensional array into a one-dimensional array, and obtain the sorted index subscript, that is
index = np.argsort(a.ravel())[:-3:-1] 得到 index 值为 [5 3]
- Next, the index obtained in one dimension is mapped to the high dimension, and the position index in the high dimension array is obtained
pos = np.unravel_index(index, a.shape) 得到 pos 值为 (array([1, 1], dtype=int64), array([2, 0], dtype=int64))
- Merge pos by column
np.column_stack(pos) 结果:[[1 2] [1 0]]
- The index
[1 2]
corresponds to the maximum value13
, and[1 0]
the corresponding value is the second largest value8
- We first expand the two-dimensional array into a one-dimensional array, and obtain the sorted index subscript, that is
- Try three-dimensional, three-dimensional (multi-dimensional) and two-dimensional steps are the same
a = np.array([ [[1, 7, 5], [8, 2, 13]], [[25, 0, 3], [50, 14, 28]] ])
index = np.argsort(a.ravel())[:-3:-1] pos = np.unravel_index(index, a.shape) print(a.ravel()) print(index) print(pos) print(np.column_stack(pos))
a.ravel(): [ 1 7 5 8 2 13 25 0 3 50 14 28] index: [ 9 11] pos: (array([1, 1], dtype=int64), array([1, 1], dtype=int64), array([0, 2], dtype=int64)) np.column_stack(pos): [[1 1 0] [1 1 2]]
[Python] Take the index of the largest values in the Numpy multidimensional array
Guess you like
Origin blog.csdn.net/weixin_42166222/article/details/119894269
Recommended
Ranking