Tom Kurushingal
Tom Kurushingal

Reputation: 6496

How do I sort an array by row?

I have an array A of the form given below:

A = [[ 4  3  2  1]
     [ 8  7  6  5]
     [12 11 10  9]
     [16 15 14 13]]

I would like to sort this array by row. The output required is:

A = [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]
     [13 14 15 16]]

I tried using the following code (but it does not work):

import numpy as np
A = np.array([[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]])
print A[np.lexsort(A, axis = 1)]

How do I sort this array by row?

Upvotes: 0

Views: 154

Answers (4)

tom10
tom10

Reputation: 69192

Numpy's sort has an axis argument that can be used to specify which axis is sorted.

import numpy as np
A = np.array([[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]])

A.sort(axis=1)

which gives:

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

sort defaults to use axis as the last axis of the array, so here it would be 1, so you don't really need to specify axis=1 in this case.

Upvotes: 1

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

Two different answers, both one-liners, are as follows:

sorted_A_1 = sorted(sorted(i) for i in A)
sorted_A_2 = [sorted(i) for i in sorted(A)]

While you may want to simply modify the existing list, these both generate a new list. The first one pipes the result of sorting each list in A to the sorted function and the second is just a list comprehension.

Also, while these may not be clearer than the answers already posted, I personally think it's helpful to see different approaches to solving a given problem!

Upvotes: 0

Kavin Eswaramoorthy
Kavin Eswaramoorthy

Reputation: 1625

A = [[ 4,  3,  2,  1],
     [12, 11, 10,  9],
     [ 8,  7,  6,  5],
     [16, 15, 14, 13]]
for i in A:
    i.sort()

A.sort()
print A

I assumed row by row means you want to sort outer list also

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

It isn't clear what you mean by "sorting by row", but you seem to want to sort the elements of the array, which you can do by iterating over it and sorting each element:

for i in A: i.sort()

If you also want to sort the outer array itself, then, well, sort it:

A.sort()

Upvotes: 3

Related Questions