简体   繁体   中英

Sort Numpy Array in Python

I have a numpy array, consisting of a flat array and value. To be clear, this is how the array looks:

x = [([1,2,3],1),([2,3,4],8),([3,4,5],3), ([4,5,6],2)]

Using numpy.sort or argsort, it is not clear to me how to sort the array above by the second thing in each element.

I want the array to look like this after sorting:

x = [([1,2,3],1),([4,5,6],2), ([3,4,5],3), ([2,3,4],8)]

Any guidance would be appreciated.

You could do -

x[x[:,1].argsort()]

Sample run -

In [768]: x
Out[768]: 
array([[[1, 2, 3], 1],
       [[2, 3, 4], 8],
       [[3, 4, 5], 3],
       [[4, 5, 6], 2]], dtype=object)

In [769]: x[x[:,1].argsort()]
Out[769]: 
array([[[1, 2, 3], 1],
       [[4, 5, 6], 2],
       [[3, 4, 5], 3],
       [[2, 3, 4], 8]], dtype=object)

If you have different number of elements in the first element, the slicing won't work and we could use list-comprehension for such a case, like so -

x[np.argsort([i[1] for i in x])]

Sample run -

In [782]: x
Out[782]: 
array([[[1, 2, 3], 1],
       [[2, 3, 4, 6], 8],
       [[3, 4, 5], 3],
       [[4, 5, 6], 2]], dtype=object)

In [783]: x[np.argsort([i[1] for i in x])]
Out[783]: 
array([[[1, 2, 3], 1],
       [[4, 5, 6], 2],
       [[3, 4, 5], 3],
       [[2, 3, 4, 6], 8]], dtype=object)

You can use Python's sorted() function.

sorted(x, key=lambda x_element: x_element[1])

How this works:

as the sorting key, you use the return value of the lambda, which is your second value in the tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM