简体   繁体   中英

Multi Dimensional Numpy Array Sorting

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]])

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]])

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