What is the numpy.partition() function from NumPy in Python?

Overview

In Python, the partition() function is used to return a partitioned copy of an array, rearranged in such a way that the values of the element in the kth position of the original array are repositioned as they would have been in a sorted array.

Additionally, all the elements that are smaller than the kth element are moved before this element and all the elements that are equal to or greater than the kth element are placed after it.

Syntax

numpy.partition(a, kth, axis=- 1, kind='introselect', order=None)

Required parameter values

The partition() function takes the following mandatory parameter values:

  • a: This represents the array that needs to be sorted.
  • kth: This represents the index position or index number of the elements to partition by.

Optional parameter values

The partition() function takes the following optional parameter values:

  • axis: This represents the axis along which the elements of the array need to be sorted. The default value sorting value is -1, which sorts the elements along the last axis.
  • kind: This represents the selection algorithm. The default value for this algorithm is introselect.
  • order: When a is an array with defined fields, this parameter value specifies which fields to compare first, second, third, and so on.

Return value

The partition() function returns an array of the same type and shape as the input array that is sorted.

Code example

import numpy as np
# creating an input array to be sorted
myarray = np.array([5, 3, 1, 4, 2])
# calling the partition() function
sortarray = np.partition(myarray, 3)
print(myarray)
print(sortarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create a 1D array called myarray.
  • Line 6: We implement the partition() function on the array, myarray, using the element in the index 3 position of the array to partition by. We assign the result to another array called sortarray.
  • Line 8: We print the input array called myarray to the console.
  • Line 9: We print the variable called sortarray to the console.

Free Resources