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 np
arr = 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]])
Answer from JaminSore on Stack OverflowUse .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 np
arr = 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.
To sort by the second column of a:
a[a[:, 1].argsort()]
@steve's answer is actually the most elegant way of doing it.
For the "correct" way see the order keyword argument of numpy.ndarray.sort
However, you'll need to view your array as an array with fields (a structured array).
The "correct" way is quite ugly if you didn't initially define your array with fields...
As a quick example, to sort it and return a copy:
In [1]: import numpy as np
In [2]: a = np.array([[1,2,3],[4,5,6],[0,0,1]])
In [3]: np.sort(a.view('i8,i8,i8'), order=['f1'], axis=0).view(np.int)
Out[3]:
array([[0, 0, 1],
[1, 2, 3],
[4, 5, 6]])
To sort it in-place:
In [6]: a.view('i8,i8,i8').sort(order=['f1'], axis=0) #<-- returns None
In [7]: a
Out[7]:
array([[0, 0, 1],
[1, 2, 3],
[4, 5, 6]])
@Steve's really is the most elegant way to do it, as far as I know...
The only advantage to this method is that the "order" argument is a list of the fields to order the search by. For example, you can sort by the second column, then the third column, then the first column by supplying order=['f1','f2','f0'].
Using lexsort:
import numpy as np
a = np.array([(3, 2), (6, 2), (3, 6), (3, 4), (5, 3)])
ind = np.lexsort((a[:,1],a[:,0]))
a[ind]
# array([[3, 2],
# [3, 4],
# [3, 6],
# [5, 3],
# [6, 2]])
a.ravel() returns a view if a is C_CONTIGUOUS. If that is true,
@ars's method, slightly modifed by using ravel instead of flatten, yields a nice way to sort a in-place:
a = np.array([(3, 2), (6, 2), (3, 6), (3, 4), (5, 3)])
dt = [('col1', a.dtype),('col2', a.dtype)]
assert a.flags['C_CONTIGUOUS']
b = a.ravel().view(dt)
b.sort(order=['col1','col2'])
Since b is a view of a, sorting b sorts a as well:
print(a)
# [[3 2]
# [3 4]
# [3 6]
# [5 3]
# [6 2]]
The title says "sorting 2D arrays". Although the questioner uses an (N,2)-shaped array, it's possible to generalize unutbu's solution to work with any (N,M) array, as that's what people might actually be looking for.
One could transpose the array and use slice notation with negative step to pass all the columns to lexsort in reversed order:
>>> import numpy as np
>>> a = np.random.randint(1, 6, (10, 3))
>>> a
array([[4, 2, 3],
[4, 2, 5],
[3, 5, 5],
[1, 5, 5],
[3, 2, 1],
[5, 2, 2],
[3, 2, 3],
[4, 3, 4],
[3, 4, 1],
[5, 3, 4]])
>>> a[np.lexsort(np.transpose(a)[::-1])]
array([[1, 5, 5],
[3, 2, 1],
[3, 2, 3],
[3, 4, 1],
[3, 5, 5],
[4, 2, 3],
[4, 2, 5],
[4, 3, 4],
[5, 2, 2],
[5, 3, 4]])
How does your "2D array" look like?
For example:
>>> a = [
[12, 18, 6, 3],
[ 4, 3, 1, 2],
[15, 8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4, 3, 1, 2],
[15, 8, 9, 6],
[12, 18, 6, 3]]
But I guess you want something like this:
>>> a = [
[12, 18, 6, 3],
[ 4, 3, 1, 2],
[15, 8, 9, 6]
]
>>> a = zip(*a)
>>> a.sort(key=lambda x: x[1])
>>> a
[(6, 1, 9),
(3, 2, 6),
(18, 3, 8),
(12, 4, 15)]
>>> a = zip(*a)
>>> a
[(6, 3, 18, 12),
(1, 2, 3, 4),
(9, 6, 8, 15)
]
Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right?-)
So I'll assume that by "2d array" you mean a list of lists, such as:
lol = [ range(10), range(2, 12), range(5, 15) ]
or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.
So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:
indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
lol[i] = [sublist[j] for j in indices]
The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.
If you actually have a different problem, there will of course be different solutions;-).