'Python Sort Array

Is it possible to sort an array with the smallest values on the bottom left and the highest on the top right?

For example :

I've this array :

[[-1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]]

the sort would be like

[[1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]
 [-1.  1.  1.]]

An other example :

[[-1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 4.  3.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]]

Would be :

[[ 1.  1.  4.]
 [ 1.  1.  3.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]
 [-1.  1.  1.]]

I Tried Numpy sort :

MyArray.sort()

But it seems not ordering this way.



Solution 1:[1]

This will get you a sorted array that is sorted from smallest to largest, running from the bottom left up each column till the top right.

import numpy as np

# Just some code to get a random, unsorted array
unsorted = np.arange(0,20)
np.random.shuffle(unsorted)
unsorted = unsorted.reshape((5,4))
print("Original Array:")
print(unsorted)

# Get the shape of the original array
array_shape = unsorted.shape
# Flatten, sort, reshape and rotate.
sorted_array = np.rot90(np.sort(unsorted.flatten()).reshape(array_shape[::-1]))

print("Sorted Array:")
print(sorted_array)

Output:

Original Array:
[[18 12  9 15]
 [ 1 19 17 13]
 [16  0 11  7]
 [ 2  6  5 14]
 [ 4  8  3 10]]
Sorted Array:
[[ 4  9 14 19]
 [ 3  8 13 18]
 [ 2  7 12 17]
 [ 1  6 11 16]
 [ 0  5 10 15]]

I'd have to give this some more thought to get a 'diagonally sorted' array.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1