This tutorial help to understand usage with the example of numpy.sort()
method. We’ll cover all the different ways to use into python application. This function returns a sorted copy of an array.
Python numpy.sort()
let’s create a simple python file and demonstrate numpy.sort()
method.
Syntax:
numpy.sort(arr, axis=- 1, kind=None, order=None)
The Parameters are:
arr : Array to be sorted.
axis : Axis along which we need an array to be started.
order : This argument specifies which fields to compare first.
kind : [‘quicksort’{default}, ‘mergesort’, ‘heapsort’]Sorting algorithm.
Sort an Single Dimensional array using numpy.sort()
Let’s sort a simple array using this method.
Importing libraries,
import numpy as np
Let’s take a NumPy array,
arr = np.array([3, 4, 5, 7, 9, 12, 14])
Let’s create a sorted array using global numpy.sort()
function:
sortedArr = np.sort(arr) print('Sorted Array : ', sortedArr) print('Original Array : ', arr)
Output:
Sorted Array : [ 3 4 5 7 9 12 14] Original Array : [ 3 4 5 7 9 12 14] ** Process exited - Return Code: 0 ** Press Enter to exit terminal
Sorting Two Dimentional array Using Numpy
let’s sort a two-dimensional array using axis parameter.
Importing libraries,
import numpy as np
Sorting using the first axis:
a = np.array([[6, 7], [8, 4]]) arr1 = np.sort(a, axis = 0) print ("Result : \n", arr1)
Sorting using the last axis:
a = np.array([[6, 7], [8, 4]]) arr2 = np.sort(a, axis = -1) print ("\nResult : \n", arr2)
Output:
Result : [[6 4] [8 7]] Result : [[6 7] [4 8]] ** Process exited - Return Code: 0 ** Press Enter to exit terminal