NumPy Basics Examples
Short, runnable programs that show numpy basics in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the NumPy Basics lesson.
1Quick ways to create arrays
You do not always need a list to start from. NumPy has helpers for common arrays, and reshape() changes the shape without changing the values.
import numpy as np
print(np.zeros(3))
print(np.ones((2, 3)))
print(np.arange(1, 6))
print(np.linspace(0, 1, 5))
print(np.arange(6).reshape(2, 3))Expected output[0. 0. 0.]
[[1. 1. 1.]
[1. 1. 1.]]
[1 2 3 4 5]
[0. 0.25 0.5 0.75 1. ]
[[0 1 2]
[3 4 5]]
2Indexing and slicing a 2-D array
Use [row, column] to reach one value. A colon on its own means "every row" or "every column", so seats[:, 2] is the whole third column.
import numpy as np
seats = np.arange(1, 13).reshape(3, 4)
print(seats)
print("Row 1:", seats[1])
print("Column 2:", seats[:, 2])
print("Row 2, column 3:", seats[2, 3])
print(seats[:2, 1:3])Expected output[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Row 1: [5 6 7 8]
Column 2: [ 3 7 11]
Row 2, column 3: 12
[[2 3]
[6 7]]
3Cleaning sensor data with a mask
Real data often marks missing values with a placeholder such as -999. A mask finds them, ~ flips the mask, and assigning through a mask replaces values in place.
import numpy as np
# -999 means "sensor error" in this data
readings = np.array([21.5, -999.0, 22.1, 23.4, -999.0, 22.8])
valid = readings != -999.0
print("Valid readings:", valid.sum(), "of", readings.size)
average = readings[valid].mean()
print("Average:", round(average, 2))
readings[~valid] = average
print(readings)Expected outputValid readings: 4 of 6
Average: 22.45
[21.5 22.45 22.1 23.4 22.45 22.8 ]
4Pass or fail for a whole class with np.where
np.where(condition, a, b) picks a where the condition is true and b elsewhere. A mask made from one array can filter another array of the same length.
import numpy as np
names = np.array(["Asha", "Ben", "Chen", "Dina", "Eli"])
scores = np.array([78, 45, 91, 52, 38])
print(np.where(scores >= 50, "pass", "fail"))
print("Passed:", names[scores >= 50])
print("Top student:", names[scores.argmax()])
print("Curved:", np.minimum(scores + 10, 100))Expected output['pass' 'fail' 'pass' 'pass' 'fail']
Passed: ['Asha' 'Chen' 'Dina']
Top student: Chen
Curved: [ 88 55 100 62 48]
Practise next
NumPy Basics exercises → Back to the lesson
NumPy Indexing and Slicing examplesNumPy Math and Broadcasting examplesPandas Basics examplesMatplotlib Basics examples