[Python] numpy arranges the arrays in order and then restores the original order

Preface

Sometimes we encounter some scenes, we need to sort the data, perform some processing, and then restore our data to the original sorting. I searched the Internet and found that there is no ready-made demo, so here is a record

One-dimensional situation
import numpy as np

arr = np.array([2, 1, 3, 5, 2, 44, 11])
print('原来顺序:', arr)

order = np.argsort(-arr)
arr = sorted(arr, reverse=True)
print('排序后顺序:',arr)

recovery_arr = np.zeros_like(arr)
for idx, num in enumerate(arr):
    recovery_arr[order[idx]] = num
print('回复原来顺序:',recovery_arr)

The output is:

原来顺序: [ 2  1  3  5  2 44 11]
排序后顺序: [44, 11, 5, 3, 2, 2, 1]
回复原来顺序: [ 2  1  3  5  2 44 11]
Multidimensional situation

If it is multi-dimensional, the principle is the same, but one more for loop is needed

import numpy as np

arr = np.array([[2, 1, 3, 5, 2, 44, 11],[2, 1, 3, 5, 2, 44, 11]])
print('原来顺序:', arr)

order = np.argsort(-arr)
for idx in range(len(arr)):
    arr[idx] = sorted(arr[idx], reverse=True)
print('排序后顺序:',arr)

recovery_arr = np.zeros_like(arr)
for idx, num in enumerate(arr):
    for jdx, n in enumerate(num):
        recovery_arr[idx, order[idx, jdx]] = n
print('回复原来顺序:',recovery_arr)
原来顺序: 
[[ 2  1  3  5  2 44 11]
 [ 2  1  3  5  2 44 11]]
排序后顺序: 
[[44 11  5  3  2  2  1]
 [44 11  5  3  2  2  1]]
回复原来顺序: 
[[ 2  1  3  5  2 44 11]
 [ 2  1  3  5  2 44 11]]

Guess you like

Origin blog.csdn.net/weixin_38705903/article/details/112475621