user3601754
user3601754

Reputation: 3862

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()"

Upvotes: 2

Views: 3938

Answers (1)

Angus Williams
Angus Williams

Reputation: 2334

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

Upvotes: 4

Related Questions