NumPy is a Python library used for numerical computing that makes array operations fast and efficient. It provides built-in functions for sorting arrays, searching for specific elements and counting occurrences of values. These functions help simplify data manipulation and analysis allowing you to perform complex operations on large datasets with ease.
Sorting
Sorting in NumPy refers to arranging array elements in a specific order, such as numerical or alphabetical order. It helps improve data organisation and makes searching and analysis more efficient, especially when working with large datasets or multi-dimensional arrays.
1. numpy.sort()
numpy.sort() method returns a sorted copy of the input array without modifying the original array. It is useful when you want sorted data while keeping the original data unchanged.
import numpy as np
arr = np.array([5, 2, 9, 1, 7])
sorted_arr = np.sort(arr)
print(sorted_arr)
Output:
[1 2 5 7 9]
2. numpy.argsort()
numpy.argsort() function returns the indices that would sort the array instead of the sorted values themselves. It is commonly used when you need to rearrange another array based on the sorted order.
import numpy as np
scores = np.array([88, 95, 70, 85])
students = np.array(["Anish", "Rahul", "Priya", "Vikram"])
sorted_indices = np.argsort(scores)
sorted_students = students[sorted_indices]
print(sorted_students)
Output:
['Priya' 'Vikram' 'Anish' 'Rahul']
3. numpy.lexsort()
This function performs an indirect stable sort using multiple sorting keys. The last key is used as the primary sort key making it useful for sorting structured or tabular data.
import numpy as np
age = np.array([25, 35, 20, 30])
salary = np.array([50000, 60000, 45000, 55000])
sorted_indices = np.lexsort((salary, age))
print(sorted_indices)
Output:
[2 0 3 1]
4. ndarray.sort()
This method sorts the array in-place meaning the original array is modified. It is memory-efficient since no new array is created.
import numpy as np
cities = np.array(["Delhi", "Mumbai", "Chennai", "Bangalore"])
cities.sort()
print(cities)
Output:
['Bangalore' 'Chennai' 'Delhi' 'Mumbai']
5. numpy.sort_complex()
numpy.sort_complex() function sorts a complex array by real part first, and if equal, by the imaginary part. It is specifically designed for handling complex numbers.
import numpy as np
arr = np.array([3+2j, 1+5j, 3+1j])
sorted_arr = np.sort_complex(arr)
print(sorted_arr)
Output:
[1.+5.j 3.+1.j 3.+2.j]
6. numpy.partition()
numpy.partition() method partially sorts the array such that the element at the given position is in its correct place. Elements smaller appear before it and larger ones after it but the order is not fully sorted.
import numpy as np
prices = np.array([1200, 500, 800, 300, 1500])
partitioned_prices = np.partition(prices, 2)
print(partitioned_prices)
Output:
[ 300 500 800 1200 1500]
7. numpy.argpartition()
numpy.argpartition() function returns the indices that would partition the array around a given position. It is useful for finding top-k or bottom-k elements efficiently.
import numpy as np
marks = np.array([78, 92, 65, 88, 70])
top_indices = np.argpartition(marks, -2)
print(marks[top_indices])
Output:
[65 70 78 88 92]
Searching
Searching in NumPy is used to locate the position of elements that satisfy a specific condition or comparison. It supports different data structures such as 1D and 2D arrays, strings, booleans and arrays with missing values. These operations help efficiently identify maximum, minimum or matching elements within large datasets.
1. numpy.argmax()
numpy.argmax() function returns the index of the maximum value in an array. We can search across the entire array or along a specific axis in multi-dimensional data.
import numpy as np
marks = np.array([[78, 85, 90],
[88, 76, 95]])
print("Input Array:\n", marks)
print("Overall max index:", np.argmax(marks))
print("Column-wise max index:", np.argmax(marks, axis=0))
print("Row-wise max index:", np.argmax(marks, axis=1))
Output:

2. numpy.nanargmax()
numpy.nanargmax() function works like argmax() but ignores NaN values while searching. It is useful when dealing with incomplete or missing data.
import numpy as np
temperatures = np.array([np.nan, 32, 45, 40])
print("Input:", temperatures)
print("Max index ignoring NaN:", np.nanargmax(temperatures))
data = np.array([[np.nan, 25],
[30, 28]])
print("2D Array:\n", data)
print("Row-wise max index:", np.nanargmax(data, axis=1))
Output:

3. numpy.argmin()
numpy.argmin() function returns the index of the minimum value in an array. It helps identify the smallest element position efficiently.
import numpy as np
prices = np.array([1200, 850, 999, 650])
print("Prices:", prices)
print("Index of lowest price:", np.argmin(prices))
Output:
Prices: [1200 850 999 650]
Index of lowest price: 3
4. numpy.nanargmin()
numpy.nanargmin() function returns the index of the minimum value while ignoring NaN values. It ensures reliable results when the dataset contains missing entries.
import numpy as np
scores = np.array([np.nan, 78, 65, 80])
print("Scores:", scores)
print("Min index ignoring NaN:", np.nanargmin(scores))
Output:
Scores: [nan 78. 65. 80.]
Min index ignoring NaN: 2
5. numpy.argwhere()
numpy.argwhere() function returns the indices of elements that satisfy a condition. The result is grouped by element, making it useful for filtering data.
import numpy as np
arr = np.array([10, 0, -5, 0, 8])
indices = np.argwhere(arr > 0)
print(indices)
Output:
[[0]
[4]]
6. numpy.nonzero()
numpy.nonzero() function returns the indices of non-zero elements in the array. It is often used for quick condition-based searches.
import numpy as np
values = np.array([10, 0, 20, 0, 30])
print("Non-zero indices:", np.nonzero(values))
Output:
Non-zero indices: (array([0, 2, 4]),)
7. numpy.flatnonzero()
numpy.flatnonzero() function returns indices of non-zero elements in the flattened array. It is useful when working with multi-dimensional arrays.
import numpy as np
matrix = np.array([[0, 1], [2, 0]])
print("Flat non-zero indices:", np.flatnonzero(matrix))
Output:
Flat non-zero indices: [1 2]
8. numpy.where()
numpy.where() function returns elements based on a condition. It can also be used to choose values from two arrays.
import numpy as np
marks = np.array([45, 72, 88, 60])
result = np.where(marks >= 60, "Pass", "Fail")
print("Result:", result)
Output:
Result: ['Fail' 'Pass' 'Pass' 'Pass']
9. numpy.searchsorted()
numpy.searchsorted() function finds the index where a value should be inserted to maintain sorted order. It is commonly used in binary search applications.
import numpy as np
sorted_scores = np.array([40, 55, 70, 85])
print("Insert position for 65:", np.searchsorted(sorted_scores, 65))
Output:
Insert position for 65: 2
10. numpy.extract()
numpy.extract() function returns elements that satisfy a given condition. It is helpful for extracting filtered data directly.
import numpy as np
ages = np.array([12, 18, 25, 15, 30])
adults = np.extract(ages >= 18, ages)
print("Adults:", adults)
Output:
Adults: [18 25 30]
Counting
Counting in NumPy involves determining how many elements meet a specific condition such as non-zero values, Boolean matches or frequency of occurrences. These operations help summarize data efficiently and extract meaningful statistical insights from arrays. NumPy optimized counting mechanisms work well with both one-dimensional and multi-dimensional data.
1. numpy.count_nonzero()
numpy.count_nonzero() function returns the number of non-zero elements in an array. It works with numeric, boolean and conditional expressions.
import numpy as np
arr = np.array([0, 10, 0, 25, 30, 0])
count = np.count_nonzero(arr)
print("Array:", arr)
print("Non-zero count:", count)
Output:
Array: [ 0 10 0 25 30 0]
Non-zero count: 3
2. numpy.bincount()
numpy.bincount() function counts occurrences of non-negative integers in an array. Each index represents the integer value and its count.
import numpy as np
numbers = np.array([1, 2, 2, 3, 3, 3, 4, 5, 10, 5])
frequency_counts = np.bincount(numbers)
print("Frequency of each number:")
for value, count in enumerate(frequency_counts):
if count > 0:
print(f"Number {value} appears {count} times")
Output:

3. numpy.unique()
numpy.unique() function is used to find the unique elements in an array. It can also return additional information such as the frequency of each unique value, the indices of their first occurrence and inverse indices making it useful for counting and data analysis.
import numpy as np
data = np.array(["apple", "banana", "apple", "orange", "banana", "apple"])
unique_items, counts = np.unique(data, return_counts=True)
print("Unique elements:", unique_items)
print("Counts:", counts)
Output:
Unique elements: ['apple' 'banana' 'orange']
Counts: [3 2 1]
You can download full code from here.