SORTING VALUES IN NUMPY

In this tutorial, we are going to learn about the sorting values in numpy. We will work with the sort method and learn how to work around axises as well as finding min and max indices value of the input array and much more through hands on examples.





What is Sorting Values in Numpy?

Numpy has the ability to sort out values. And we will work with a few sorting functions in Numpy to learn more about them.

numpy-sorting

Sort Function

The basic sort function in numpy is used for returning a copy of a sorted array. It has the following syntax:

np.sort(array, axis=0)

Where a is the array to be sorted, and axis is the axis that you want to choose. We will be working with two of the parameters right now to understand the sort function.

import numpy as np
arr = np.array([[3,7,5,8],[9,1,3,1]])
print('Our array is:')
print(arr)

print(“\n”)
print(np.sort(arr, axis=1))

Output:

Our array is:
[[3 7 5 8]
 [9 1 3 1]]

array([[3, 5, 7, 8],
       [1, 1, 3, 9]])




Argmin and Argmax Function

The argmin() and argmax() function returns the indices of the minimum and maximum value of the array input.

import numpy as np
arr = np.array([1,2,3,4,5,6,7,8])
print('Our array is:')
print(arr)

print("\n")
print("Applying argmin function")
print(np.argmin(arr))


print("\n")
print("Applying argmax function")
print(np.argmax(arr))

Output:

Our array is:
[1 2 3 4 5 6 7 8]

Applying argmin function
0

Applying argmax function
7

Non-Zero in Numpy

This function returns the indices of non-zero array elements. For example:

import numpy as np
arr = np.array([0,1,2,3,4,5,0,6,7,8,0,0])
print('Our array is:')
print(arr)

print("\n")
print("Applying nonzero function")
print(np.nonzero(arr))

Output:

Our array is:
[0 1 2 3 4 5 0 6 7 8 0 0]

Applying nonzero function
(array([1, 2, 3, 4, 5, 7, 8, 9]),)