NumPy partition() function

The partition() function is used to split up the input array accordingly as per the given arguments.

  • This function returns the partitioned copy of the input array.
  • In the paritioned copy of the array, the elements are rearranged in such a way that the element in kth position takes the position where it would be, had the array was sorted.
  • All elements smaller than the kth element are moved before this element and all the elements that are equal or greater to it are moved behind it.
  • In case there are data elements with value equal to the kth element, then the ordering of the elements in the two partitions stays undefined.

Syntax of numpy.partition():

The syntax required to use this method is as follows:

numpy.partition(arr, kth, axis, kind, order)

Parameters:

let us now take a look at the parameters of this function:

  • arr This parameter indicates the input array that is to be sorted.
  • kth It is an integer or sequence of integers. This parameter indicates the index of the element around which the partition needs to be performed.
  • axis This parameter indicates the axis along which the elements would be sorted. The default value of this parameter is -1( means it sort along the last axis).
  • kind This parameter is used to define the kind of sorting you want to perform.The default value of this parameter is ‘introselect’.
  • order For an array arr with fields defined in it, this argument is used to specify which fields to compare first, second, and so on.

Returned Values:

This Function will return an Array of the same type and shape as the Input Array.

Example 1:

The code snippet is as follows where we will use partition() function:

import numpy as np

inp_ar = np.array([2, 0, 1, 5, 4, 9, 78, 34]) 
print ("The Input array : ") 
print(inp_ar)

output = np.partition(inp_ar, 5) 
print ("The Output partitioned array : ")
print(output) 

Output:

The Input array : 
[ 2 0 1 5 4 9 78 34] 
The Output partitioned array :
 [ 4 2 1 0 5 9 34 78]

It is concluded from the output of the above code snippet that all the elements less than the element at 5th position which is 9 are placed to the left side of 9 and all the elements greater than 9 are placed to the right of the separator element (5th element).

Also, note that the order of elements appearing in the output array is undefined.

Example 2:

import numpy as np

arr = np.array([7, 4, 8, 1, 10, 13])
print("The Input array is :")
print(arr)

output = np.partition(arr, (1, 3))
print("The Output Partitioned array is :")
print(output)

Output:

The Input array is :
 [7 4 8 1 10 13] 
The Output Partitioned array is : 
[1 4 7 8 10 13]
Follow Us On