How to sort 2D array (numpy.ndarray) based to the second column in python? [duplicate] How to sort 2D array (numpy.ndarray) based to the second column in python? [duplicate] numpy numpy

How to sort 2D array (numpy.ndarray) based to the second column in python? [duplicate]


Use .argsort() it returns an numpy.array of indices that sort the given numpy.array. You call it as a function or as a method on your array. For example, suppose you have

import numpy as nparr = np.array([[-0.30565392, -0.96605562],                [ 0.85331367, -2.62963495],                [ 0.87839643, -0.28283675],                [ 0.72676698,  0.93213482],                [-0.52007354,  0.27752806],                [-0.08701666,  0.22764316],                [-1.78897817,  0.50737573],                [ 0.62260038, -1.96012161],                [-1.98231706,  0.36523876],                [-1.07587382, -2.3022289 ]])

You can now call .argsort() on the column you want to sort, and it will give you an array of row indices that sort that particular column which you can pass as an index to your original array.

>>> arr[arr[:, 1].argsort()]array([[ 0.85331367, -2.62963495],       [-1.07587382, -2.3022289 ],       [ 0.62260038, -1.96012161],       [-0.30565392, -0.96605562],       [ 0.87839643, -0.28283675],       [-0.08701666,  0.22764316],       [-0.52007354,  0.27752806],       [-1.98231706,  0.36523876],       [-1.78897817,  0.50737573],       [ 0.72676698,  0.93213482]])

You can equivalently use numpy.argsort()

>>> arr[np.argsort(arr[:, 1])]array([[ 0.85331367, -2.62963495],       [-1.07587382, -2.3022289 ],       [ 0.62260038, -1.96012161],       [-0.30565392, -0.96605562],       [ 0.87839643, -0.28283675],       [-0.08701666,  0.22764316],       [-0.52007354,  0.27752806],       [-1.98231706,  0.36523876],       [-1.78897817,  0.50737573],       [ 0.72676698,  0.93213482]])


sorted(Data, key=lambda row: row[1]) should do it.