# Sorting Arrays
# Fast Sorting in NumPy: np.sort and np.argsort
import numpy as np
a = np.array([1, 9, 0, 7, 3, 5])
sort = np.sort(a)
print(sort)
[0 1 3 5 7 9]
# If you want the sorted index then use np.argsort
index = np.argsort(a)
print(index)
[2 0 4 5 3 1]
# Sorting along rows or columns
X = rand.randint(0, 10, (4, 6))
print(X)
print("-----------------------------------")
# sort each column of X
a = np.sort(X, axis=0)
print(a)
print("-----------------------------------")
# sort each row of X
b = np.sort(X, axis =1)
print(b)
[[7 8 7 3 4 8] [6 3 8 8 5 1] [3 3 3 2 6 5] [5 2 5 6 1 5]] ----------------------------------- [[3 2 3 2 1 1] [5 3 5 3 4 5] [6 3 7 6 5 5] [7 8 8 8 6 8]] ----------------------------------- [[3 4 7 7 8 8] [1 3 5 6 8 8] [2 3 3 3 5 6] [1 2 5 5 5 6]]
# Partial Sorts: Partitioning
x = np.array([7, 2, 3, 1, 6, 5, 4])
print(x)
print("------------------------------")
a = np.partition(x, 3)
print(a)
# NumPy provides this in the np.partition function.
# np.partition takes an array and a number K; the result is a new array with the smallest K values to the left of the partition,
# and the remaining values to the right, in arbitrary order:
[7 2 3 1 6 5 4] ------------------------------ [2 1 3 4 6 5 7]
b = np.partition(X, 2, axis=1)
print(b)
[[3 4 7 7 8 8] [1 3 5 8 8 6] [2 3 3 3 6 5] [1 2 5 6 5 5]]