python - Sort 2D numpy array (by row) based on another 2D array of same shape -


with 2 arrays:

x = np.array([[1,2,3], [2,3,1]]) x array([[1, 2, 3],        [2, 3, 1]]) y = np.array([['a','b', 'c'], ['a','b', 'c']]) y array([['a', 'b', 'c'],        ['a', 'b', 'c']],       dtype='|s1') 

i trying sort y based on values of x row row without looping through each row, i.e

xord = x.argsort()  in range(x.shape[0]):     print y[i][xord[i]]  ['a' 'b' 'c'] ['c' 'a' 'b'] 

is there more efficient way sort array y based on corresponding row order of x?

first can use np.argsort indices of x elements based on position after sorting,then can elements y based on indices of x np.take():

>>> s=np.argsort(x) >>> np.take(y,s) array([['a', 'b', 'c'],        ['c', 'a', 'b']],        dtype='|s1') 

Popular posts from this blog