What you will learn
After learning to create NumPy arrays, it is time to work with them. You will do element-wise calculations, change shapes, select values with conditions, sort arrays and apply bonuses with broadcasting.
Start with import numpy as np. NumPy must be installed in the Python environment you use. The linked browser editor may not support third-party packages; use a NumPy-enabled environment for these examples.
Step 1 of 9
Array arithmetic
NumPy operations act element by element. Unlike a Python list, adding a scalar to an array adds it to every element.
import numpy as np
scores = np.array([50, 70, 90])
print(scores + 5) # [55 75 95]
print(scores * 2) # [100 140 180]
print(scores / 10) # [5. 7. 9.]Step 2 of 9
Reshape and flatten
Reshape changes the dimensions without changing element count: 3 × 4 = 12. flatten() returns a copy; ravel() returns a view when possible.
a = np.arange(1, 13)
matrix = a.reshape(3, 4)
print(matrix)
print(matrix.shape) # (3, 4)
print(matrix.flatten()) # independent copy
print(matrix.ravel()) # view when possibleStep 3 of 9
Transpose
Transpose exchanges rows and columns. For a 2D array, its shape goes from (rows, columns) to (columns, rows).
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape) # (2, 3)
print(a.T)
print(a.T.shape) # (3, 2)Step 4 of 9
Boolean comparison and filtering
A comparison produces a Boolean mask. Use the mask inside square brackets to select matching values.
marks = np.array([45, 78, 32, 91, 66])
print(marks >= 50)
print(marks[marks >= 50]) # [78 91 66]Step 5 of 9
Combining conditions
Use & for element-wise AND, | for OR, and ~ for NOT. Put each comparison in parentheses, not Python's and/or.
marks = np.array([45, 78, 32, 91, 66])
selected = marks[(marks >= 60) & (marks <= 90)]
print(selected) # [78 66]Step 6 of 9
np.where()
np.where(condition, yes, no) chooses a result per element. With only a condition, it can return matching index positions.
marks = np.array([45, 78, 32, 91, 66])
print(np.where(marks >= 40, "Pass", "Fail"))
print(np.where(marks < 40)[0]) # indices of failuresStep 7 of 9
Sorting and sorting indices
np.sort returns sorted values; np.argsort returns indices that would put the original array in sorted order.
a = np.array([55, 12, 83, 41])
print(np.sort(a)) # [12 41 55 83]
print(np.argsort(a)) # [1 3 0 2]Step 8 of 9
Broadcasting made simple
Broadcasting aligns shapes from the right. A (3,) array can be added to each row of a (2, 3) array.
marks = np.array([[70, 80, 90], [60, 75, 85]])
bonus = np.array([5, 2, 3])
print(marks + bonus)
# [[75 82 93]
# [65 77 88]]Step 9 of 9
Mini project: Student Marks Analyzer
Keep each student in a row and each subject in a column. Run the example, then edit the scores and bonus amounts to see the result.
import numpy as np
marks = np.array([[70, 80, 90], [35, 45, 55], [88, 92, 79]])
bonus = np.array([5, 2, 3])
adjusted = np.minimum(marks + bonus, 100)
print("Adjusted marks:\n", adjusted)
print("Subject averages:", adjusted.mean(axis=0))
print("Student averages:", adjusted.mean(axis=1))
print("Pass all subjects:", np.all(adjusted >= 40, axis=1))
print("Highest overall:", adjusted.max())
print("Sorted averages:", np.sort(adjusted.mean(axis=1)))Try it yourself
- Make an array with 12 values; reshape it into a 4 × 3 matrix.
- Filter numbers that are divisible by 3.
- Use
np.where()to classify marks as Pass or Fail. - Find descending sort order using
np.argsort(). - Add subject-specific bonus marks to a 3-student matrix.
Hints
Use reshape(4,3), a[a % 3 == 0], np.where(marks >= 40, "Pass", "Fail"), and np.argsort(a)[::-1].
Where to go next
Next suggested lesson: Cleaning Data with NumPy — missing values, duplicates, outliers and data preparation for Pandas.
Review the previous lesson