numpy argsort code example

Example 1: .argsort() python

x = np.array([[0,3],[2,2]])

>>> ind = np.argsort(x, axis=1)  # sorts along last axis (across)
>>> ind
array([[0, 1],
       [0, 1]])
>>> np.take_along_axis(x, ind, axis=1)  # same as np.sort(x, axis=1)
array([[0, 3],
       [2, 2]])

Example 2: numpy argwhere

test = np.array([-2,3,4,-8,1])
np.argwhere(test < 0)

>>>
array([[0],
       [3]], dtype=int64)

Example 3: python argsort

def g(seq):
    # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3383106#3383106
    #lambda version by Tony Veijalainen
    return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]