user3601754 user3601754 - 2 months ago 5
Python Question

sorting arrays in numpy by row

I would like to sort an array in numpy by the first row.

For example :

import numpy as np

test = np.array([[1334.71601720318, 930.9757468052002, 1018.7038817663818],
[0.0, 1.0, 2.0],
[ np.array([[ 667, 1393],
[1961, 474]]),
np.array([[ 673, 1389],
[ 847, 1280]]),
np.array([[ 726, 1077],
[ 898, 961]])]], dtype=object)


I want to sort the row :

[1334.71601720318, 930.9757468052002, 1018.7038817663818]


to obtain :

np.array([[930.9757468052002, 1018.7038817663818, 1334.71601720318],
[1.0, 2.0 ,0.0],
[ np.array([[ 673, 1389],
[ 847, 1280]]),
np.array([[ 726, 1077],
[ 898, 961]])],
np.array([[ 667, 1393],
[1961, 474]])], dtype=object)


---- EDIT LATER ----

I tried with : sorted(test, key=lambda row: row[1])
But i got an error message : "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

Answer

I think test[:, np.argsort( test[0] ) ] should do the trick.