/*
* Licensed to
Oliver, Wisconsin
Q:
What is the us
The present invent
Q:
How can I chanQ:
Python: How to sort a 2d array according to its 1d array?
I would like to sort a 2d array according to one of its 1d array (index of the array in 1d array).
For example, I have a 2d array:
a = np.array([[1,3],[2,4],[3,5],[4,5]])
I would like to sort by the first element in the 1d array (not sorting them):
b = np.array([0,1,0,1])
and get the result:
b = np.array([[0,3],[1,4],[0,5],[1,5]])
or
b = [[0,3],[1,4],[0,5],[1,5]]
What should I do?
A:
In order to preserve the order of the first dimension you have to use the np.lexsort method.
b = np.lexsort(a)
>>> a = np.array([[1,3],[2,4],[3,5],[4,5]])
>>> b = np.lexsort(a)
>>> b
array([[0, 3],
[1, 4],
[0, 5],
[1, 5]])
A:
Simply multiply each 2D array by b:
b = np.array([[0,1],[0,1]])
np.multiply(a,b)
which gives
array([[0, 3],
[1, 4],
[0, 5],
[1, 5]])
You could also use argsort:
b = np.argsort(a)[:,:,0]
np.multiply(a,b)
which gives
array([[0, 3],
[1, 4],
[0, 5],
[1, 5]])
The [:,:,0] slices of argsort selects the rows, the columns, and the first column of the resulting array.
A:
Another solution that preserve the first dimension order:
>>> import numpy as np
>>> a = np.array([[1,3],[2,4],[3,5],[4,5]])
>>> b = np.array([0,1,0,1])
>>> b[::-1]
array([0, 1, 0, 1])
>>> np.take(b, a, axis=1).T
array([[0, 3],
[1, 4],
[0, 5],
[1, 5]])
np.take does the job by selecting the columns, then reversing the dimensions of the 2D array.
Note that the np.take solution works only if the 1D array order is from 0 to N.
Another way is using np.argsort() and np.transpose():
>>> a = np.array([[1,3],[2,4],[3,5],[4,5]])
>>> np.argsort(a, axis=1)[:,:,0]
array([0, 1, 0, 1])
>>> a[np.argsort(a, axis=1)[:,:,0]]
array([[0, 3],
[1, 4],
[0, 5],
[1, 5]])
This solution is limited to use the lexicographical order:
>>> np.argsort(a, axis=1)[:,:,0].argsort()
array([0, 1, 0, 1])
But, if your arrays are numeric, you can use np.lexsort():
>>> np.lexsort(a)
array([0, 3, 1, 4, 0, 5, 1, 5])
However, it does not preserve the order if your array is not sorted with lexicographical order.