NumPy Tutorial menu

NumPy Sorting, Searching and Filtering

This lesson shows how to put arrays in order, find values in them and keep only the values you need.

Sorting

np.sort() returns a sorted copy. For descending order, reverse the result with [::-1].

Example

python
import numpy as np

prices = np.array([450, 120, 999, 75, 300])
print(np.sort(prices))
print(np.sort(prices)[::-1])

names = np.array(["Zara", "Ali", "Hina"])
print(np.sort(names))
Output
[ 75 120 300 450 999]
[999 450 300 120  75]
['Ali' 'Hina' 'Zara']

np.argsort() gives the indexes that would sort the array. This is handy when you want to sort one array by another:

Example

python
import numpy as np

students = np.array(["Ali", "Sara", "Omar"])
marks = np.array([72, 91, 85])
order = np.argsort(marks)[::-1]
print(students[order])
Output
['Sara' 'Omar' 'Ali']

Filtering With Boolean Masks

A comparison gives an array of True / False. Put that inside the square brackets, and NumPy keeps only the True items. This is called boolean indexing or a mask.

Example

python
import numpy as np

marks = np.array([45, 78, 52, 30, 90, 66])
passed = marks[marks >= 50]
print(passed)
print("Number passed:", (marks >= 50).sum())
Output
[78 52 90 66]
Number passed: 4

True counts as 1 when you add, so .sum() counts how many items match.

Combining Conditions

Use & for "and", the pipe symbol for "or" and ~ for "not". Put each condition in brackets.

Example

python
import numpy as np

ages = np.array([12, 17, 25, 34, 61, 70])
print(ages[(ages >= 18) & (ages < 60)])
print(ages[~(ages >= 18)])
Output
[25 34]
[12 17]

Do not use the words and / or with arrays. They work on single True/False values only and will raise an error. Use & and the pipe symbol instead.

np.where()

np.where(condition) gives the indexes where the condition is true. With three arguments, it picks between two values item by item:

Example

python
import numpy as np

marks = np.array([45, 78, 52, 30])
print(np.where(marks < 50))
print(np.where(marks >= 50, "Pass", "Fail"))
Output
(array([0, 3]),)
['Fail' 'Pass' 'Pass' 'Fail']

Unique Values

Example

python
import numpy as np

cities = np.array(["Karachi", "Lahore", "Karachi", "Multan", "Lahore"])
values, counts = np.unique(cities, return_counts=True)
print(values)
print(counts)
Output
['Karachi' 'Lahore' 'Multan']
[2 2 1]

Joining and Splitting

FunctionWhat it does
np.concatenate([a, b])Joins arrays end to end
np.vstack([a, b])Stacks as rows (one on top of the other)
np.hstack([a, b])Joins side by side
np.split(a, n)Splits into n equal parts

Example

python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate([a, b]))
print(np.vstack([a, b]))
print(np.split(np.arange(6), 3))
Output
[1 2 3 4 5 6]
[[1 2 3]
 [4 5 6]]
[array([0, 1]), array([2, 3]), array([4, 5])]

Exercise

Exercise

arr = np.array([5, 12, 8, 20]). What does arr[arr > 10] return?

Learn NumPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp