2

I have (5,5) np.array like below.

>>> a
array([[23, 15, 11,  0, 17],
       [ 1,  2, 20,  4,  6],
       [16, 22,  8, 10, 18],
       [ 7, 12, 13, 14,  5],
       [ 3,  9, 21, 19, 24]])

I want to multi dimensional sort the np.array to look like below.

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

To do that I did,

  1. flatten() the array.
  2. Sort the flatted array.
  3. Reshape to (5,5)

In my method I feel like it is a bad programming practice.Are there any sophisticated way to do that task? Thank you.

>>> a array([[23, 15, 11,  0, 17],
       [ 1,  2, 20,  4,  6],
       [16, 22,  8, 10, 18],
       [ 7, 12, 13, 14,  5],
       [ 3,  9, 21, 19, 24]])

>>> a_flat = a.flatten()
>>> a_flat
array([23, 15, 11,  0, 17,  1,  2, 20,  4,  6, 16, 22,  8, 10, 18,  7, 12,
       13, 14,  5,  3,  9, 21, 19, 24])

>>> a_sort = np.sort(a_flat)
>>> a_sorted = a_sort.reshape(5,5)
>>> a_sorted
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
1
  • I find it absolutely OK Commented Jul 13, 2017 at 15:54

1 Answer 1

3

We could get a flattened view with np.ravel() and then sort in-place with ndarray.sort() -

a.ravel().sort()

Being everything in-place, it avoids creating any temporary array and also maintains the shape, which avoids any need of reshape.

Sample run -

In [18]: a
Out[18]: 
array([[23, 15, 11,  0, 17],
       [ 1,  2, 20,  4,  6],
       [16, 22,  8, 10, 18],
       [ 7, 12, 13, 14,  5],
       [ 3,  9, 21, 19, 24]])

In [19]: a.ravel().sort()

In [20]: a
Out[20]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
Sign up to request clarification or add additional context in comments.

6 Comments

@Bodhi94 Yup! Added doc reference.
Thanks a lot @Divakar. You are great !!
Watch out, though - it's not always possible to take a flattened view of an array, in which case ravel will silently make a copy. For example, if you try to sort numpy.arange(25).reshape([5, 5]).T this way, it will silently have no effect.
@user2357112 Well that's a special case. It doesn't have its own data, with its OWNDATA flag being False. But good point.
It's more about memory layout than whether the array owns its data - an array that doesn't own its data can still be sorted this way if the memory layout works out (for example, if it's C-contiguous), and an array that does own its data can't be sorted this way if the memory layout doesn't work out (for example, if it's F-contiguous).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.