I am sorting a large multidimensional numpy array along an axis. After some computations I'd like to undo the sorting with the values themselves being different to when I did the initial sorting.
Initially I tried by simply reversing the sorting indices, but if the array was already sorted correctly in the first place this of course doesn't make any sense, see below code.
import numpy as np
array = np.random.rand(100,2,4)
array.out = array
arg = array.argsort(axis=1)
arg_rev = arg.argsort(axis=1)
# this solution is based on https://github.com/numpy/numpy/issues/4724
for i in range(0, array.shape[2]):
tmp = array[:,:,i]
array.out[:,:,i] = tmp[np.arange(np.shape(tmp)[0])[:, np.newaxis], arg_ftc_rev[:,:,i]]
I would like to combine this solution with the one from undo or reverse argsort(), python without having to loop over an additional array index.
# ( a = np.random.randint(0,10,10)
# aa = np.argsort(a)
# aaa = np.argsort(aa) )
# e.g.
array.out[:,:,i] = tmp[np.arange(np.shape(tmp)[0])[:, np.newaxis], arg_ftc[:,:,i][arg_ftc_rev[:,:,i]]
but this does not work, as it results in the wrong shape.