Module 1, topic 9, week 5, Tuesday
NumPy continued: slicing, broadcasting, and vectorized operations
Slices of arrays and tables, views and copies, calculations on whole arrays, masks, axis, and broadcasting
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-09-numpy-slicing-broadcasting.ipynb, 51 KB
Practice notebook
The 15 practice problems with a hint and a hidden solution for each.
topic-09-practice.ipynb, 25 KB
Introduction: slicing, vectorized operations and broadcasting
A beginner-friendly guide to the second half of NumPy. In the last lesson you created arrays and reached single elements by index. In this lesson you take whole parts of an array with slices, calculate with whole arrays at once instead of writing loops, choose elements with a condition, summarise rows and columns, and learn the rule called broadcasting that lets arrays of different shapes work together. It starts from the simplest examples and gets harder step by step. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know how to create an array, what shape means, and how to index a 1D and a 2D array (a[2], table[1, 2]).
What you will learn
- 1.Slicing a 1D array and a 2D array: rows, columns and smaller tables
- 2.Why a slice is a view of the same data, and when to use
copy - 3.Vectorized operations: arithmetic on whole arrays without loops
- 4.Comparisons, and choosing elements with a boolean mask
- 5.
np.wherefor "this value or that value" - 6.Summaries of rows and columns with
axis - 7.Broadcasting: how arrays of different shapes are combined
- 8.15 solved problems and practice problems
1Slicing a 1D array
A slice takes a part of an array. It works as with lists: a[start:stop], and the element at stop is not included.
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| value | 10 | 20 | 30 | 40 | 50 | 60 |
| negative | -6 | -5 | -4 | -3 | -2 | -1 |
a[1:4] starts at index 1 and stops before index 4, so it takes 20, 30 and 40.import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[1:4])
print(a[:3])
print(a[3:])
print(a[-2:])Output
[20 30 40] [10 20 30] [40 50 60] [50 60]
Change it and run: print 30 and 40, then the last three elements.
An empty place means "from the start" or "to the end". a[:3] is the first three elements, and a[-2:] is the last two.
1.1A step
The third number is the step: a[start:stop:step].
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[::2])
print(a[1::2])
print(a[::-1])Output
[10 30 50] [20 40 60] [60 50 40 30 20 10]
Change it and run: print every third element with a[::3].
a[::2] takes every second element, and a[::-1] gives the array reversed.
Choose a slice and see which elements it takes.
a = np.array([10, 20, 30, 40, 50, 60]) print(a[1:4])
| 0 | 1 | 2 | 3 | 4 | 5 |
| 10 | 20 | 30 | 40 | 50 | 60 |
| -6 | -5 | -4 | -3 | -2 | -1 |
Result: [20 30 40]
The element at the stop index is never taken. An empty place means "from the start" or "to the end", and with a negative step the slice walks backwards.
1.2A slice never gives an IndexError
If the numbers are too big, the slice simply stops at the end:
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[4:100])
print(a[10:])Output
[50 60] []
Change it and run: try a[-100:2]. A start that is too small is no problem either.
1.3Changing a part of an array
A slice on the left side of = changes all its elements at once:
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
a[1:4] = 0
print(a)
a[-2:] = [7, 8]
print(a)Output
[10 0 0 0 50 60] [10 0 0 0 7 8]
Change it and run: set the first two elements to -1.
One value is put into every place of the slice. A list must have exactly as many items as the slice.
| Slice | Meaning |
|---|---|
a[1:4] | from index 1 up to, not including, index 4 |
a[:3] | the first 3 elements |
a[3:] | from index 3 to the end |
a[-2:] | the last 2 elements |
a[::2] | every second element |
a[::-1] | all elements, reversed |
Try it yourself
Show a hint
np.arange(1, 11) gives 1 to 10. The slice is a[2:6]. Which numbers do you expect before you run it?Show the solution
import numpy as np
a = np.arange(1, 11)
print(a[2:6])Output
[3 4 5 6]
2Slicing a 2D array
A 2D array takes two slices, separated by a comma: table[rows, columns]. Rows first, then columns, as with indexes.
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 1 | 2 | 3 | 4 |
| row 1 | 5 | 6 | 7 | 8 |
| row 2 | 9 | 10 | 11 | 12 |
table[0:2, 1:3]: the rows 0 and 1, the columns 1 and 2. In both directions the stop index is not included.2.1Whole rows
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table)
print(table[0:2])
print(table[1:])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] [[1 2 3 4] [5 6 7 8]] [[ 5 6 7 8] [ 9 10 11 12]]
Change it and run: print the last row with a slice, table[2:], and with an index, table[2]. Count the brackets in the two outputs.
With only one slice, you get whole rows.
2.2A whole column
A colon alone, :, means "all of them". So table[:, 1] reads: all rows, column 1.
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[:, 1])
print(table[:, -1])
print(table[1, :])Output
[ 2 6 10] [ 4 8 12] [5 6 7 8]
Change it and run: print column 0, then row 2.
A column comes back as a 1D array. table[1, :] is the same as table[1]: row 1, all columns.
2.3A smaller table
Two slices together cut out a block:
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[0:2, 1:3])
print(table[1:, :2])Output
[[2 3] [6 7]] [[ 5 6] [ 9 10]]
Change it and run: cut out the bottom right corner: 7, 8, 11, 12.
table[0:2, 1:3] means: rows 0 and 1, columns 1 and 2.
Choose the rows and the columns, and see what the slice takes.
table = np.arange(1, 13).reshape(3, 4) print(table[0:2, 1:3])
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 1 | 2 | 3 | 4 |
| row 1 | 5 | 6 | 7 | 8 |
| row 2 | 9 | 10 | 11 | 12 |
Result
[[2 3] [6 7]]
Rows 0, 1, columns 1, 2. Shape of the result: (2, 2).
2.4Several columns, and steps
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[:, 0:2])
print(table[:, ::2])
print(table[::-1])Output
[[ 1 2] [ 5 6] [ 9 10]] [[ 1 3] [ 5 7] [ 9 11]] [[ 9 10 11 12] [ 5 6 7 8] [ 1 2 3 4]]
Change it and run: print the last two columns.
table[::-1] reverses the order of the rows.
2.5The shape of the result
An index removes a dimension. A slice keeps it:
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[:, 1].shape)
print(table[:, 1:2].shape)
print(table[0:2, 1:3].shape)Output
(3,) (3, 1) (2, 2)
Change it and run: print the shape of table[1:, :] and of table[1, :].
table[:, 1] is a 1D array with 3 elements. table[:, 1:2] is still a table, with 3 rows and 1 column.
2.6Changing a part of a table
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
table[:, 0] = 0
table[2, 1:] = 99
print(table)Output
[[ 0 2 3 4] [ 0 6 7 8] [ 0 99 99 99]]
Change it and run: set the last column to -1.
| You write | You get |
|---|---|
table[0:2] | rows 0 and 1 |
table[:, 1] | column 1, as a 1D array |
table[1, :] | row 1 (the same as table[1]) |
table[0:2, 1:3] | a block: rows 0-1, columns 1-2 |
table[:, :2] | the first two columns |
table[::-1] | the rows in reverse order |
table[:, 0] = 0 | sets a whole column |
Try it yourself
table, print the first row, then the first column, then the block with the numbers 6, 7, 10 and 11.Show a hint
table[0], the first column is table[:, 0]. The block is in the rows 1 and 2 and the columns 1 and 2: table[1:, 1:3].Show the solution
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[0])
print(table[:, 0])
print(table[1:, 1:3])Output
[1 2 3 4] [1 5 9] [[ 6 7] [10 11]]
3A slice is a view, not a copy
This is the biggest difference between arrays and lists. A slice of a list is a new list. A slice of an array is a view: a window onto the same data.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
part = a[1:4]
part[0] = 999
print(part)
print(a)Output
[999 30 40] [ 10 999 30 40 50]
Change it and run: change part[0] = 999 to part[:] = 0. Three elements of a become 0.
We changed part, and a changed too. NumPy does this on purpose: data sets can be huge, and copying them at every step would be slow.
The same with a list, for comparison:
numbers = [10, 20, 30, 40, 50]
part = numbers[1:4]
part[0] = 999
print(part)
print(numbers)Output
[999, 30, 40] [10, 20, 30, 40, 50]
3.1copy makes a separate array
When you want to change a part without touching the original, add .copy():
import numpy as np
a = np.array([10, 20, 30, 40, 50])
part = a[1:4].copy()
part[0] = 999
print(part)
print(a)Output
[999 30 40] [10 20 30 40 50]
Change it and run: remove .copy() and run it again.
part = a[1:4]
A view: one set of data
part = a[1:4].copy()
A copy: two separate arrays
part[0] = 999. On the left, part is a window onto the data of a, so the 999 is in a too.3.2It is the same in 2D
import numpy as np
table = np.arange(1, 10).reshape(3, 3)
first_row = table[0]
first_row[0] = 100
print(table)Output
[[100 2 3] [ 4 5 6] [ 7 8 9]]
Change it and run: add .copy() after table[0]. The table stays as it was.
| Gives | Changing it changes the original? | |
|---|---|---|
A slice, a[1:4] | a view | yes |
A row or column, table[0], table[:, 1] | a view | yes |
a[1:4].copy() | a copy | no |
A list of indexes, a[[0, 2]] | a copy | no |
A mask, a[a > 3] (Part 6) | a copy | no |
Try it yourself
a by accident. Change one line so that first becomes [0 6 7] and a stays [5 6 7 8 9].Show a hint
a[:3] is a view of a. Add .copy() to that line.Show the solution
import numpy as np
a = np.array([5, 6, 7, 8, 9])
first = a[:3].copy()
first[0] = 0
print(first)
print(a)Output
[0 6 7] [5 6 7 8 9]
4Vectorized operations: arithmetic on whole arrays
With a list, a calculation on every item needs a loop. With an array you write the calculation once, and NumPy does it for every element. This is called a vectorized operation.
4.1An array and a number
import numpy as np
prices = np.array([10, 20, 30, 40])
print(prices + 5)
print(prices * 2)
print(prices / 4)
print(prices ** 2)Output
[15 25 35 45] [20 40 60 80] [ 2.5 5. 7.5 10. ] [ 100 400 900 1600]
Change it and run: print the prices minus 10, and the prices divided by 10.
The result is a new array. prices itself is not changed. Division always gives decimals.
4.2The same with a loop
prices = [10, 20, 30, 40]
doubled = []
for price in prices:
doubled.append(price * 2)
print(doubled)Output
[20, 40, 60, 80]
Four lines became one: prices * 2. The array version is shorter, easier to read, and much faster with large data.
4.3Careful: a list behaves differently
import numpy as np
numbers = [1, 2, 3]
print(numbers * 2)
print(np.array(numbers) * 2)Output
[1, 2, 3, 1, 2, 3] [2 4 6]
Change it and run: add print(numbers + 5) as the last line and read the error.
* 2 repeats a list, but multiplies an array. numbers + 5 with a list is even an error. This is one more reason to turn data into an array before calculating.
4.4Two arrays
When two arrays have the same shape, the operation is done element by element: the first with the first, the second with the second, and so on.
import numpy as np
prices = np.array([10, 20, 30])
amounts = np.array([2, 1, 4])
print(prices + amounts)
print(prices * amounts)
print((prices * amounts).sum())Output
[12 21 34] [ 20 20 120] 160
Change it and run: change the amounts to [1, 1, 1]. What is the total now?
The last line is the total cost of a shopping cart, without a loop.
| prices | 10 | 20 | 30 |
|---|---|---|---|
| amounts | 2 | 1 | 4 |
| prices * amounts | 20 | 20 | 120 |
4.5Tables work the same way
import numpy as np
a = np.array([
[1, 2],
[3, 4],
])
b = np.array([
[10, 20],
[30, 40],
])
print(a + b)
print(a * 10)Output
[[11 22] [33 44]] [[10 20] [30 40]]
Change it and run: print b - a and b / a.
4.6The shapes must fit
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20])
print(a + b)Error
ValueError: operands could not be broadcast together with shapes (3,) (2,)
Three elements cannot be paired with two. (Which different shapes do fit is the subject of Part 8.)
4.7Changing the array itself
a = a + 5 and a += 5 both store the result back in a:
import numpy as np
a = np.array([1, 2, 3])
a += 5
print(a)
a = a * 2
print(a)Output
[6 7 8] [12 14 16]
Change it and run: use a -= 1, then a *= 3.
4.8Math functions for whole arrays
NumPy has its own math functions that work on every element:
import numpy as np
a = np.array([1, 4, 9, 16])
print(np.sqrt(a))
b = np.array([-3, 2, -1])
print(np.abs(b))
c = np.array([2.567, 3.141, 9.999])
print(np.round(c, 1))Output
[1. 2. 3. 4.] [3 2 1] [ 2.6 3.1 10. ]
Change it and run: round c to 2 decimals, then to 0 decimals.
| Operation | What it does | Example |
|---|---|---|
a + 5, a - 5 | adds / subtracts a number from every element | prices + 5 |
a * 2, a / 2 | multiplies / divides every element | prices * 2 |
a ** 2 | the power of every element | prices ** 2 |
a + b, a * b | element by element (same shape) | prices * amounts |
np.sqrt(a) | the square root of every element | np.sqrt(a) |
np.abs(a) | every element without its minus sign | np.abs(b) |
np.round(a, n) | every element rounded to n decimals | np.round(c, 1) |
Try it yourself
widths and heights, print the area of every rectangle, then the total area.Show a hint
widths * heights multiplies element by element. Store it in areas, then print areas and areas.sum().Show the solution
import numpy as np
widths = np.array([2, 5, 10])
heights = np.array([3, 4, 1.5])
areas = widths * heights
print(areas)
print(areas.sum())Output
[ 6. 20. 15.] 41.0
5Comparisons give True and False
A comparison is vectorized too. It checks every element and gives an array of True and False:
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print(grades >= 60)
print(grades == 78)Output
[ True False True True True] [False False True False False]
Change it and run: print which grades are below 50.
Such an array of True and False is called a boolean mask.
5.1Counting with a mask
True counts as 1 and False as 0, so sum counts the True values:
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
passed = grades >= 60
print(passed.sum())
print(passed.mean())Output
4 0.8
Change it and run: count the grades above 80.
4 students passed. The mean of a mask is the share of True values: 0.8 means 80%.
5.2any and all
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print((grades < 50).any())
print((grades >= 40).all())Output
True True
Change it and run: ask whether all grades are at least 50.
any asks "is at least one True?", all asks "are all True?".
5.3Comparing two arrays
import numpy as np
first = np.array([70, 80, 90])
second = np.array([75, 80, 60])
print(second > first)
print(first == second)Output
[ True False False] [False True False]
Change it and run: print second >= first.
Try it yourself
temps, print the mask of the days above 24 degrees, then how many such days there are, then whether any day is below 10 degrees.Show a hint
temps > 24 in a variable. Print it, then its .sum(). The last line is (temps < 10).any().Show the solution
import numpy as np
temps = np.array([18, 25, 31, 22, 35, 12])
hot = temps > 24
print(hot)
print(hot.sum())
print((temps < 10).any())Output
[False True True False True False] 3 False
6Choosing elements with a mask
Put a mask inside the square brackets, and you get only the elements where the mask is True. This is called boolean indexing, and it is how data is filtered in NumPy and later in pandas.
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
mask = grades >= 60
print(mask)
print(grades[mask])Output
[ True False True True True] [85 78 60 95]
Usually the condition is written directly inside the brackets:
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print(grades[grades >= 60])
print(grades[grades < 50])
print(grades[grades % 2 == 0])Output
[85 78 60 95] [42] [42 78 60]
Change it and run: print the grades above 80, then the odd grades.
Read grades[grades >= 60] as: "the grades where the grade is at least 60".
6.1A mask from one array, used on another
The two arrays must have the same length:
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran", "Nigar"])
grades = np.array([85, 42, 78, 60, 95])
print(names[grades >= 80])Output
['Aylin' 'Nigar']
Change it and run: print the names of the students with a grade below 60.
6.2Two conditions: &, | and ~
For arrays, use & for "and", | for "or" and ~ for "not". Every condition needs its own parentheses:
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print(grades[(grades >= 60) & (grades < 90)])
print(grades[(grades < 50) | (grades > 90)])
print(grades[~(grades >= 60)])Output
[85 78 60] [42 95] [42]
Change it and run: print the grades from 40 to 80, both included.
The words and, or and not do not work with arrays:
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print(grades[(grades >= 60) and (grades < 90)])Error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
| For single values | For arrays |
|---|---|
and | & |
or | | |
not | ~ |
Choose a condition. The mask says True or False for every grade.
grades = np.array([85, 42, 78, 60, 95]) print(grades[grades >= 60])
| grades | 85 | 42 | 78 | 60 | 95 |
|---|---|---|---|---|---|
| mask | True | False | True | True | True |
Result: [85 78 60 95]
4 of 5 values in the mask are True, so the result has 4 elements. The grades with False are left out.
6.3Changing the chosen elements
A mask on the left side of = changes only the chosen elements:
import numpy as np
values = np.array([5, -3, 8, -1, 0])
values[values < 0] = 0
print(values)Output
[5 0 8 0 0]
Change it and run: set every value above 4 to 4.
6.4A mask on a table
import numpy as np
table = np.array([
[3, 8, 5],
[12, 7, 10],
])
print(table > 6)
print(table[table > 6])Output
[[False True False] [ True True True]] [ 8 12 7 10]
Change it and run: choose the even numbers of the table.
The chosen elements of a table come back as a 1D array.
6.5np.where: this value or that value
np.where(condition, a, b) builds a new array: a where the condition is True, b where it is False. It is an if/else for a whole array.
import numpy as np
grades = np.array([85, 42, 78, 60, 95])
print(np.where(grades >= 60, "pass", "fail"))
print(np.where(grades > 90, 100, grades))Output
['pass' 'fail' 'pass' 'pass' 'pass'] [ 85 42 78 60 100]
Change it and run: change the pass mark from 60 to 80.
The second line gives 100 to everybody above 90 and keeps the other grades as they are.
Try it yourself
names = np.array(["Aylin", "Murad", "Leyla", "Kamran"]) and grades = np.array([85, 42, 78, 45]), print the names of the students with a grade below 50.Show a hint
grades, and it is used on names: names[grades < 50].Show the solution
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran"])
grades = np.array([85, 42, 78, 45])
print(names[grades < 50])Output
['Murad' 'Kamran']
7Summaries of rows and columns: axis
You know sum, mean, min and max for a whole array. For a table, you often want the result for every column or for every row. The argument axis chooses:
| exam 0 | exam 1 | exam 2 | axis=1 | |
|---|---|---|---|---|
| student 0 | 80 | 90 | 70 | 240 |
| student 1 | 60 | 50 | 100 | 210 |
| axis=0 | 140 | 140 | 170 | 450 |
sum(axis=0) adds down the rows and leaves one sum for every column (every exam). sum(axis=1) adds along the columns and leaves one sum for every row (every student). Without axis, the whole table gives 450.import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
print(grades.sum())
print(grades.sum(axis=0))
print(grades.sum(axis=1))Output
450 [140 140 170] [240 210]
Change it and run: add a third student, [70, 70, 70]. Which of the three results get longer?
Without axis, the whole table gives one number. With axis=0, there is one sum for every column (every exam). With axis=1, there is one sum for every row (every student).
How to remember it: the axis you name is the one that disappears. The shape is (2, 3). axis=0 removes the 2, so 3 results are left. axis=1 removes the 3, so 2 results are left.
7.1The other summaries work the same way
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
print(grades.mean(axis=0))
print(grades.mean(axis=1))
print(grades.max(axis=1))
print(grades.min(axis=0))Output
[70. 70. 85.] [80. 70.] [ 90 100] [60 50 70]
Change it and run: print the lowest grade of every student.
7.2argmax with an axis
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
print(grades.argmax(axis=1))
print(grades.argmax(axis=0))Output
[1 2] [0 0 1]
Change it and run: print grades.argmin(axis=1): the weakest exam of every student.
The first line is the best exam of every student. The second line is the best student of every exam.
7.3Sorting
np.sort gives a sorted copy. The original stays as it is:
import numpy as np
a = np.array([30, 10, 50, 20])
print(np.sort(a))
print(np.sort(a)[::-1])
print(a)Output
[10 20 30 50] [50 30 20 10] [30 10 50 20]
Change it and run: print the two largest values: np.sort(a)[::-1][:2].
| You write | You get |
|---|---|
table.sum() | one number for the whole table |
table.sum(axis=0) | one result for every column |
table.sum(axis=1) | one result for every row |
mean, min, max, argmax, argmin | take axis in the same way |
np.sort(a) | a sorted copy |
Try it yourself
sales each row is a shop and each column a day. Print the total of every shop, then the total of every day, then the index of the best day of every shop.Show a hint
axis=1. Every day is every column: axis=0. The best day of every shop: sales.argmax(axis=1).Show the solution
import numpy as np
sales = np.array([
[5, 8, 3],
[7, 2, 9],
])
print(sales.sum(axis=1))
print(sales.sum(axis=0))
print(sales.argmax(axis=1))Output
[16 18] [12 10 12] [1 2]
8Broadcasting
In Part 4, two arrays needed the same shape. But prices * 2 worked too, although 2 is a single number. NumPy stretched the 2 so that it fits every element. This stretching is called broadcasting.
[10, 20, 30] * 2 is calculated like [10, 20, 30] * [2, 2, 2]
Nothing is really copied. NumPy only behaves as if the small value were repeated.
8.1A row and a table
A 1D array with as many elements as the table has columns is used for every row:
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
row = np.array([10, 20, 30])
print(table + row)Output
[[11 22 33] [14 25 36]]
Change it and run: change row to [100, 0, -100].
table
row
table + row
8.2A column and a table
To use one value for every row, the small array must be a column: a table with one column. reshape(-1, 1) makes it:
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
column = np.array([100, 200]).reshape(-1, 1)
print(column)
print(table + column)Output
[[100] [200]] [[101 102 103] [204 205 206]]
Change it and run: multiply instead of adding: table * column.
100 was added to every element of row 0, and 200 to every element of row 1.
8.3The rule
Write the two shapes under each other, lined up on the right. Go through the pairs of numbers. The shapes fit when, in every pair, the numbers are equal or one of them is 1. A missing number counts as 1.
| First shape | Second shape | Fits? | Why |
|---|---|---|---|
(2, 3) | a number | yes | a single number fits everything |
(2, 3) | (3,) | yes | 3 and 3 are equal |
(2, 3) | (2, 1) | yes | 3 and 1: one of them is 1. 2 and 2 are equal |
(2, 3) | (2,) | no | 3 and 2 are different, and none is 1 |
(3,) | (2,) | no | 3 and 2 are different |
The size 1 is the one that gets stretched.
Choose what to add to the table, and see whether the shapes fit.
table = np.array([[1, 2, 3], [4, 5, 6]]) print(table + np.array([10, 20, 30]))
| table | 2 | 3 |
|---|---|---|
| second: (3,) | 3 | |
| pair | missing: counts as 1 | equal |
table
the second one, stretched
the result
Every pair fits, so NumPy uses the second array as if it had the shape (2, 3).
8.4When the shapes do not fit
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
values = np.array([100, 200])
print(table + values)Error
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
The table has 3 columns, and values has 2 elements. NumPy lines shapes up on the right, so it tries to use values as a row, and that does not fit. The fix is the column from above: values.reshape(-1, 1).
8.5What broadcasting is used for
Subtracting the mean of every column from that column, in one line:
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
[70, 70, 70],
])
means = grades.mean(axis=0)
print(means)
print(grades - means)Output
[70. 70. 80.] [[ 10. 20. -10.] [-10. -20. 20.] [ 0. 0. -10.]]
Change it and run: subtract the largest grade of every exam instead: grades.max(axis=0).
grades has the shape (3, 3) and means has the shape (3,): one mean for every column, used for every row. The result shows how far every grade is from the average of its exam. You will see this step again and again in machine learning.
Try it yourself
Show a hint
table.mean(axis=0). It has 3 elements, as many as the table has columns, so it can be subtracted from the table directly.Show the solution
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table - table.mean(axis=0))Output
[[-3. -3. -3.] [ 0. 0. 0.] [ 3. 3. 3.]]
9Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.
Expecting a slice to be a copy
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) part = a[1:4] part[0] = 999 print(part) print(a) # prints: [999 30 40], [ 10 999 30 40 50]
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) part = a[1:4].copy() part[0] = 999 print(part) print(a) # prints: [999 30 40], [10 20 30 40 50]
Changing the slice changes the original. Use a[1:4].copy().
Thinking the stop index is included
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[1:3]) # prints: [20 30]
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[1:4]) # prints: [20 30 40]
One element is missing. a[1:4] gives the indexes 1, 2, 3.
table[1][:2] instead of table[1, :2]
Wrong
import numpy as np table = np.arange(1, 13).reshape(3, 4) print(table[1][:2]) # prints: [5 6]
Right
import numpy as np table = np.arange(1, 13).reshape(3, 4) print(table[1, :2]) # prints: [5 6]
Works here, but fails for columns. One pair of brackets: table[rows, columns].
table[:][1] for a column
Wrong
import numpy as np table = np.arange(1, 13).reshape(3, 4) print(table[:][1]) # prints: [5 6 7 8]
Right
import numpy as np table = np.arange(1, 13).reshape(3, 4) print(table[:, 1]) # prints: [ 2 6 10]
You get row 1, not column 1. Write table[:, 1].
and / or between masks
Wrong
import numpy as np grades = np.array([85, 42, 78, 60, 95]) print(grades[(grades >= 60) and (grades < 90)])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Right
import numpy as np grades = np.array([85, 42, 78, 60, 95]) print(grades[(grades >= 60) & (grades < 90)]) # prints: [85 78 60]
ValueError: the truth value is ambiguous. Use & and |.
No parentheses around the conditions
Wrong
import numpy as np a = np.array([1, 2, 3, 4, 5, 6]) print(a[a > 2 & a < 5])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Right
import numpy as np a = np.array([1, 2, 3, 4, 5, 6]) print(a[(a > 2) & (a < 5)]) # prints: [3 4]
ValueError, or a wrong result. Write (a > 2) & (a < 5).
if a > 5: with a whole array
Wrong
import numpy as np
a = np.array([3, 8, 5])
if a > 5:
print("large")ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Right
import numpy as np
a = np.array([3, 8, 5])
if (a > 5).any():
print("at least one is large")
# prints: at least one is largeValueError: the truth value is ambiguous. Use (a > 5).any() or (a > 5).all().
Arrays with shapes that do not fit
Wrong
import numpy as np a = np.array([1, 2, 3]) b = np.array([10, 20]) print(a + b)
ValueError: operands could not be broadcast together with shapes (3,) (2,)
Right
import numpy as np a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) print(a.shape, b.shape) print(a + b) # prints: (3,) (3,), [11 22 33]
ValueError: could not be broadcast. Check both shapes first.
Mixing up axis=0 and axis=1
Wrong
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
# the total of every student (every row)
print(grades.sum(axis=0))
# prints: [140 140 170]Right
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
# the total of every student (every row)
print(grades.sum(axis=1))
# prints: [240 210]Results for columns instead of rows. axis=0: for every column. axis=1: for every row.
numbers 2 with a list
Wrong
numbers = [1, 2, 3] print(numbers * 2) # prints: [1, 2, 3, 1, 2, 3]
Right
import numpy as np numbers = np.array([1, 2, 3]) print(numbers * 2) # prints: [2 4 6]
The list is repeated. Make it an array first.
A list of the wrong length into a slice
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) a[1:4] = [7, 8]
ValueError: could not broadcast input array from shape (2,) into shape (3,)
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) a[1:4] = [7, 8, 9] print(a) # prints: [10 7 8 9 50]
ValueError. The list needs as many items as the slice has.
A mask of another length
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) mask = np.array([True, False, True]) print(a[mask])
IndexError: boolean index did not match indexed array along axis 0; size of axis is 5 but size of corresponding boolean axis is 3
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) mask = a > 25 print(a[mask]) # prints: [30 40 50]
IndexError. The mask must come from an array of the same length.
A column with the wrong brackets:
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table[:][1])
print(table[:, 1])Output
[5 6 7 8] [ 2 6 10]
table[:] is the whole table, and [1] then takes row 1. Only table[:, 1] is the column.
Conditions without parentheses:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
print(a[a > 2 & a < 5])Error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
& is calculated before > and <, so Python reads this in a way nobody wanted. Write a[(a > 2) & (a < 5)].
if with a whole array:
import numpy as np
a = np.array([3, 8, 5])
if a > 5:
print("large")Error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
a > 5 is three answers, and if needs one. Say which one you mean: (a > 5).any() or (a > 5).all().
A list of the wrong length into a slice:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
a[1:4] = [7, 8]Error
ValueError: could not broadcast input array from shape (2,) into shape (3,)
A mask of another length:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
mask = np.array([True, False, True])
print(a[mask])Error
IndexError: boolean index did not match indexed array along axis 0; size of axis is 5 but size of corresponding boolean axis is 3
10Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
10.1Level 1: Easy
Problem 1: The first three and the last three
import numpy as np
a = np.arange(1, 11)
print(a[:3])
print(a[-3:])Output
[1 2 3] [ 8 9 10]
Change it and run: print the elements 4, 5, 6 and 7.
Problem 2: Every element doubled
import numpy as np
a = np.array([4, 8, 15, 16, 23, 42])
print(a * 2)Output
[ 8 16 30 32 46 84]
Change it and run: print half of every element.
Problem 3: The even numbers
import numpy as np
a = np.arange(1, 11)
print(a[a % 2 == 0])Output
[ 2 4 6 8 10]
Change it and run: print the numbers that can be divided by 3.
Problem 4: One column of a table
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table)
print(table[:, 2])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] [ 3 7 11]
Change it and run: print the last row, then the last column.
Problem 5: Celsius to Fahrenheit
import numpy as np
celsius = np.array([0, 10, 25, 37, 100])
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit)Output
[ 32. 50. 77. 98.6 212. ]
Change it and run: add -40 to the list. At -40 both scales show the same number.
Why: the formula is written once, and NumPy applies it to every temperature.
10.2Level 2: Medium
Problem 6: How many passed, and who?
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran", "Nigar"])
grades = np.array([85, 42, 78, 55, 95])
passed = grades >= 60
print("Passed:", passed.sum())
print(names[passed])
print("Average of those who passed:", grades[passed].mean())Output
Passed: 3 ['Aylin' 'Leyla' 'Nigar'] Average of those who passed: 86.0
Change it and run: change the pass mark to 50.
Why: the mask is made once and used three times: for counting, on the names, and on the grades.
Problem 7: The total price of a cart
import numpy as np
prices = np.array([1.5, 0.8, 2.0, 4.0])
amounts = np.array([2, 5, 1, 3])
costs = prices * amounts
print(costs)
print("Total:", costs.sum())Output
[ 3. 4. 2. 12.] Total: 21.0
Change it and run: set every amount to 1.
Problem 8: A 20% discount on expensive products
import numpy as np
prices = np.array([40, 120, 75, 200, 90])
new_prices = np.where(prices > 100, prices * 0.8, prices)
print(new_prices)Output
[ 40. 96. 75. 160. 90.]
Change it and run: make the discount 50%.
Why: np.where takes the discounted price where the condition is true, and the old price everywhere else.
Problem 9: Negative numbers become zero
import numpy as np
values = np.array([4, -2, 7, -9, 0, 3])
cleaned = values.copy()
cleaned[cleaned < 0] = 0
print(cleaned)
print(values)Output
[4 0 7 0 0 3] [ 4 -2 7 -9 0 3]
Change it and run: remove .copy() and look at the last line.
Why: the copy keeps the original data safe. Without .copy(), cleaned and values would be the same array.
Problem 10: The average of every student and of every exam
import numpy as np
grades = np.array([
[85, 90, 78],
[92, 60, 88],
[70, 75, 95],
])
print("Students:", grades.mean(axis=1))
print("Exams:", grades.mean(axis=0))Output
Students: [84.33333333 80. 80. ] Exams: [82.33333333 75. 87. ]
Change it and run: round both results to 1 decimal: np.round(grades.mean(axis=1), 1).
Why: each row is a student, so axis=1 gives one average for every row. Each column is an exam, so axis=0 gives one average for every column.
10.3Level 3: Medium-Hard
Problem 11: The best student by average
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla"])
grades = np.array([
[85, 90, 78],
[92, 60, 88],
[70, 75, 95],
])
averages = grades.mean(axis=1)
best = averages.argmax()
print(np.round(averages, 1))
print(names[best], "has the best average")Output
[84.3 80. 80. ] Aylin has the best average
Change it and run: change one of Murad's grades to 100.
Problem 12: Values between two limits
import numpy as np
temps = np.array([12, 25, 31, 18, 22, 35, 8])
nice = temps[(temps >= 18) & (temps <= 25)]
print(nice)
print(nice.size, "nice days")Output
[25 18 22] 3 nice days
Change it and run: change the limits to 10 and 20.
Why: two conditions joined with &, each in its own parentheses.
Problem 13: Every number as a share of the total
import numpy as np
sales = np.array([200, 300, 500])
shares = sales / sales.sum() * 100
print(shares)Output
[20. 30. 50.]
Change it and run: add a fourth sale, 1000.
Why: sales.sum() is a single number, so it is broadcast to every element.
Problem 14: A bonus for every exam
Each row is a student, each column an exam. Exam 0 gets 5 extra points, exam 1 gets 0 and exam 2 gets 10. No grade may be above 100.
import numpy as np
grades = np.array([
[85, 90, 78],
[92, 60, 95],
])
bonus = np.array([5, 0, 10])
new_grades = grades + bonus
new_grades[new_grades > 100] = 100
print(new_grades)Output
[[ 90 90 88] [ 97 60 100]]
Change it and run: give every exam 10 extra points: bonus = 10.
Why: bonus has one value for every column, so broadcasting uses it for every row. The mask then cuts the grades that went above 100.
Problem 15: How far is every grade from the student's own average?
import numpy as np
grades = np.array([
[80, 90, 70],
[60, 50, 100],
])
averages = grades.mean(axis=1).reshape(-1, 1)
print(averages)
print(grades - averages)Output
[[80.] [70.]] [[ 0. 10. -10.] [-10. -20. 30.]]
Change it and run: subtract the average of every exam instead: axis=0, and no reshape.
Why: there is one average for every row, so it must be a column with the shape (2, 1). Then it is broadcast across the three exams of each student.
11Practice problems (try them yourself)
Fifteen problems in three levels. Press Run to try your code, then Check. Problems that read input are checked with several test inputs.
Easy
One slice, one calculation, one condition.
- 1.Read a line of numbers into an array and print it reversed.Examples:
1 2 3 4 5gives[5 4 3 2 1]7gives[7]10 20gives[20 10]Show a hint
A slice with the step -1 walks backwards:a[::-1].Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a[::-1])Output
[5 4 3 2 1]
- 2.Read a line of numbers into an array and print every number multiplied by 3.Examples:
1 2 3gives[3 6 9]0gives[0]-4 5gives[-12 15]Show a hint
No loop is needed. Write the calculation on the whole array:a * 3.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a * 3)Output
[3 6 9]
- 3.Create the numbers 1 to 12 reshaped into 3 rows and 4 columns. Print the last column.
Show a hint
np.arange(1, 13).reshape(3, 4)makes the table. All rows, last column:table[:, -1].Show one possible solution
Pythonimport numpy as np table = np.arange(1, 13).reshape(3, 4) print(table[:, -1])Output
[ 4 8 12]
- 4.Read a line of numbers into an array and print only the numbers larger than 10.Examples:
5 12 30 10 11gives[12 30 11]1 2 3gives[]11gives[11]Show a hint
The conditiona > 10gives a mask. Put it inside the brackets:a[a > 10].Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a[a > 10])Output
[12 30 11]
- 5.Given
prices = np.array([10, 20, 30, 40]), print the prices with 18% tax added (multiply by 1.18).Show a hint
One multiplication for the whole array:prices * 1.18.Show one possible solution
Pythonimport numpy as np prices = np.array([10, 20, 30, 40]) print(prices * 1.18)Output
[11.8 23.6 35.4 47.2]
Medium
Counting with a mask, a block of a table, np.where and axis.
- 6.Read a line of numbers into an array. Print how many of them are negative.Examples:
3 -1 -5 0 2gives21 2 3gives0-1 -2 -3gives3Show a hint
a < 0is a mask, andsumcounts itsTruevalues:(a < 0).sum().Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print((a < 0).sum())Output
2
- 7.Create the numbers 1 to 20 reshaped into 4 rows and 5 columns. Print the block made of the first two rows and the last two columns.
Show a hint
The first two rows are:2, the last two columns are-2:. Both in one pair of brackets:table[:2, -2:].Show one possible solution
Pythonimport numpy as np table = np.arange(1, 21).reshape(4, 5) print(table[:2, -2:])Output
[[ 4 5] [ 9 10]]
- 8.Read a line of grades into an array. Print an array with
"pass"for every grade of at least 50 and"fail"for the others.Examples:85 42 50 49gives['pass' 'fail' 'pass' 'fail']50gives['pass']49gives['fail']Show a hint
np.where(condition, a, b)chooses between two values for every element:np.where(grades >= 50, "pass", "fail").Show one possible solution
Pythonimport numpy as np grades = np.array(list(map(int, input().split()))) print(np.where(grades >= 50, "pass", "fail"))Output
['pass' 'fail' 'pass' 'fail']
- 9.Read a line of numbers into an array. Print the numbers that are larger than the mean of the array.Examples:
1 2 3 4 5gives[4 5]10 10 10gives[]5gives[]Show a hint
a.mean()is one number, soa > a.mean()is a mask. Use it inside the brackets.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a[a > a.mean()])Output
[4 5]
- 10.Create the numbers 1 to 12 reshaped into 3 rows and 4 columns. Print the sum of every row and the sum of every column, in this order, each on its own line.
Show a hint
One result for every row isaxis=1. One result for every column isaxis=0.Show one possible solution
Pythonimport numpy as np table = np.arange(1, 13).reshape(3, 4) print(table.sum(axis=1)) print(table.sum(axis=0))Output
[10 26 42] [15 18 21 24]
Medium-Hard
Two conditions, two arrays, a table of grades and a function.
- 11.Read a line of numbers into an array. Replace every number above 100 with 100 and print the array.Examples:
50 150 100 101 99gives[ 50 100 100 100 99]1 2 3gives[1 2 3]200gives[100]Show a hint
A mask on the left side of=changes only the chosen elements:a[a > 100] = 100.np.where(a > 100, 100, a)gives the same result as a new array.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) a[a > 100] = 100 print(a)Output
[ 50 100 100 100 99]
- 12.Read a line of numbers into an array. Print the numbers that are at least 10 and at most 20.Examples:
5 10 15 20 25gives[10 15 20]9 21gives[]10gives[10]Show a hint
Two conditions joined with&, each in its own parentheses:(a >= 10) & (a <= 20).Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a[(a >= 10) & (a <= 20)])Output
[10 15 20]
- 13.Read two lines of numbers of the same length into two arrays: prices and amounts. Print the total cost.Examples:
10 20 30, 2 1 4gives1605, 3gives151 1 1, 0 0 0gives0Show a hint
prices * amountsmultiplies element by element: the cost of every product. Then add the costs up with.sum().Show one possible solution
Pythonimport numpy as np prices = np.array(list(map(int, input().split()))) amounts = np.array(list(map(int, input().split()))) print((prices * amounts).sum())Output
160
- 14.Given a grade table where each row is a student and each column an exam, print the average of every student, rounded to 1 decimal, and the index of the student with the highest average. Two lines.
Show a hint
One average for every row:grades.mean(axis=1). Round it withnp.round(averages, 1). The index of the highest one isaverages.argmax().Show one possible solution
Pythonimport numpy as np grades = np.array([ [70, 80, 90], [95, 85, 99], [60, 75, 71], ]) averages = grades.mean(axis=1) print(np.round(averages, 1)) print(averages.argmax())Output
[80. 93. 68.7] 1
- 15.Write a function
normalize(a)that returns the array with its smallest value subtracted from every element and the result divided by the difference between the largest and the smallest value. The smallest value becomes 0 and the largest becomes 1.Examples:10 20 30gives[0. 0.5 1. ]0 5 10 20gives[0. 0.25 0.5 1. ]3 1 2gives[1. 0. 0.5]Show a hint
Storea.min()anda.max()first. Then one line on the whole array:(a - smallest) / (largest - smallest).Show one possible solution
Pythonimport numpy as np def normalize(a): smallest = a.min() largest = a.max() return (a - smallest) / (largest - smallest) a = np.array(list(map(int, input().split()))) print(normalize(a))Output
[0. 0.5 1. ]
12Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
13Quick summary
| Concept | What it does | Example |
|---|---|---|
| 1D slice | a part of an array | a[1:4], a[::-1] |
| 2D slice | rows, then columns | table[0:2, 1:3] |
: alone | all rows or all columns | table[:, 1] |
| View | a slice shares its data with the original | part = a[1:4] |
copy | a separate array | a[1:4].copy() |
| Vectorized operation | a calculation on every element, no loop | prices * 2, a + b |
np.sqrt, np.abs, np.round | math on every element | np.round(c, 1) |
| Comparison | an array of True and False | grades >= 60 |
| Mask | chooses the elements where it is True | grades[grades >= 60] |
&, |, ~ | and, or, not for masks | (a > 2) & (a < 5) |
np.where | this value or that value | np.where(a > 0, a, 0) |
axis=0 / axis=1 | one result for every column / every row | table.sum(axis=0) |
np.sort | a sorted copy | np.sort(a) |
| Broadcasting | a smaller shape is stretched to fit | table + row |