I need to sort by the first column in descending order an array. To be specific my code is:
>>> x = np.array([[2, 3], [1998,5], [1998,7]])
>>> x = x[np.argsort(x[:,0])]
but the output is
array([[ 2, 3],
[1998, 5],
[1998, 7]])
but I need it in descending order. Can someone explain me how to do that?
EDIT: @Babyburger suggested this solution :
x = x[np.argsort(x[:,0])][::-1]
that give
array([[1998, 7],
[1998, 5],
[ 2, 3]])
it could be fine, but i would like that where the value on the first column is the same, the order is not changed. So the output would be
array([[1998, 5],
[1998, 7],
[ 2, 3]])
is there a simple way to do that?
in this particular requirement you can use python's sorted
which is stable:
a = np.array([[2, 3], [1998,5], [1998,7]])
res = np.array(sorted(a, key= lambda x: -x[0]))
it does: use the first element of each row for comparison (by lambda
accessor) and negate it for decreasing order. By stability, the rows will preserve order if the first element is the same
ouput:
[[1998 5]
[1998 7]
[ 2 3]]
EDIT: btw if you wanted to sort by the following columns whenever the preceeding ones are identical (all of the same ordering):
a = np.array([[2, 3], [1998,5], [1998,7]])
res = np.array(sorted(a, key=lambda x:(-x).tolist()))
this converts the rows to lists and then uses sequence comparison. Note in this example it will be sorted decreasingly (hence (-x)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With