Asiman Data School

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

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. 1.Slicing a 1D array and a 2D array: rows, columns and smaller tables
  2. 2.Why a slice is a view of the same data, and when to use copy
  3. 3.Vectorized operations: arithmetic on whole arrays without loops
  4. 4.Comparisons, and choosing elements with a boolean mask
  5. 5.np.where for "this value or that value"
  6. 6.Summaries of rows and columns with axis
  7. 7.Broadcasting: how arrays of different shapes are combined
  8. 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.

index012345
value102030405060
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.
Python
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].

Python
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])
The elements with their indexes; the chosen elements are highlighted
012345
102030405060
-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:

Python
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:

Python
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.

Changing a part of an array
SliceMeaning
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

Create the numbers from 1 to 10 and print the elements from index 2 up to, not including, index 6.
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
Python
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 0col 1col 2col 3
row 01234
row 15678
row 29101112
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

Python
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.

Python
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:

Python
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.

rows
columns
table = np.arange(1, 13).reshape(3, 4)
print(table[0:2, 1:3])
The table with its row and column numbers; the chosen elements are highlighted
col 0col 1col 2col 3
row 01234
row 15678
row 29101112

Result

[[2 3]
 [6 7]]

Rows 0, 1, columns 1, 2. Shape of the result: (2, 2).

2.4Several columns, and steps

Python
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:

Python
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

Python
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.

Changing a part of a table
You writeYou 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] = 0sets a whole column

Try it yourself

From table, print the first row, then the first column, then the block with the numbers 6, 7, 10 and 11.
Show a hint
The first row is 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
Python
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.

Python
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:

Python
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():

Python
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

a
10999304050part

part = a[1:4].copy()

A copy: two separate arrays

a
1020304050
part
9993040
Both pictures show the arrays after 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

Python
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.

It is the same in 2D
GivesChanging it changes the original?
A slice, a[1:4]a viewyes
A row or column, table[0], table[:, 1]a viewyes
a[1:4].copy()a copyno
A list of indexes, a[[0, 2]]a copyno
A mask, a[a > 3] (Part 6)a copyno

Try it yourself

This code changes 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
Python
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

Python
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

Python
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

Python
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.

Python
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.

prices102030
amounts214
prices * amounts2020120
Read it column by column: 10 × 2, 20 × 1, 30 × 4. NumPy pairs the elements by their position, so both arrays need the same shape.

4.5Tables work the same way

Python
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

Python
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:

Python
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:

Python
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.

Math functions for whole arrays
OperationWhat it doesExample
a + 5, a - 5adds / subtracts a number from every elementprices + 5
a * 2, a / 2multiplies / divides every elementprices * 2
a ** 2the power of every elementprices ** 2
a + b, a * belement by element (same shape)prices * amounts
np.sqrt(a)the square root of every elementnp.sqrt(a)
np.abs(a)every element without its minus signnp.abs(b)
np.round(a, n)every element rounded to n decimalsnp.round(c, 1)

Try it yourself

From 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
Python
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:

Python
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:

Python
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

Python
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

Python
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

From 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
Store temps > 24 in a variable. Print it, then its .sum(). The last line is (temps < 10).any().
Show the solution
Python
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.

Python
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:

Python
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:

Python
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:

Python
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:

Python
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()
Two conditions: &, | and ~
For single valuesFor 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])
The grades and, under each one, the value of the mask; the chosen grades are highlighted
grades8542786095
maskTrueFalseTrueTrueTrue

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:

Python
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

Python
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.

Python
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

Given 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
The mask comes from grades, and it is used on names: names[grades < 50].
Show the solution
Python
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 0exam 1exam 2axis=1
student 0809070240
student 16050100210
axis=0 140140170450
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.
Python
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

Python
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

Python
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:

Python
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].

Sorting
You writeYou 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, argmintake axis in the same way
np.sort(a)a sorted copy

Try it yourself

In 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
Every shop is every row: axis=1. Every day is every column: axis=0. The best day of every shop: sales.argmax(axis=1).
Show the solution
Python
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:

Python
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

123
456

row

102030
102030

table + row

112233
142536
The row has one value for every column, so it is used for every row of the table. The dashed row is never really made: NumPy only behaves as if it were there.

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:

Python
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.

The rule
First shapeSecond shapeFits?Why
(2, 3)a numberyesa single number fits everything
(2, 3)(3,)yes3 and 3 are equal
(2, 3)(2, 1)yes3 and 1: one of them is 1. 2 and 2 are equal
(2, 3)(2,)no3 and 2 are different, and none is 1
(3,)(2,)no3 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]))
The two shapes lined up on the right, compared pair by pair
table23
second: (3,)3
pairmissing: counts as 1equal

table

123
456

the second one, stretched

102030
102030

the result

112233
142536

Every pair fits, so NumPy uses the second array as if it had the shape (2, 3).

8.4When the shapes do not fit

Python
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:

Python
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

Given a 3 by 3 table of numbers, subtract from every element the mean of its column, and print the result.
Show a hint
One mean for every column: 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
Python
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 large

ValueError: 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:

Python
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:

Python
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:

Python
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:

Python
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:

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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?

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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.

Python
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?

Python
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. 1.Read a line of numbers into an array and print it reversed.Examples: 1 2 3 4 5 gives [5 4 3 2 1]7 gives [7]10 20 gives [20 10]
    Show a hint
    A slice with the step -1 walks backwards: a[::-1].
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a[::-1])

    Output

    [5 4 3 2 1]
  2. 2.Read a line of numbers into an array and print every number multiplied by 3.Examples: 1 2 3 gives [3 6 9]0 gives [0]-4 5 gives [-12 15]
    Show a hint
    No loop is needed. Write the calculation on the whole array: a * 3.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a * 3)

    Output

    [3 6 9]
  3. 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
    Python
    import numpy as np
    
    table = np.arange(1, 13).reshape(3, 4)
    print(table[:, -1])

    Output

    [ 4  8 12]
  4. 4.Read a line of numbers into an array and print only the numbers larger than 10.Examples: 5 12 30 10 11 gives [12 30 11]1 2 3 gives []11 gives [11]
    Show a hint
    The condition a > 10 gives a mask. Put it inside the brackets: a[a > 10].
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a[a > 10])

    Output

    [12 30 11]
  5. 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
    Python
    import 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.

  1. 6.Read a line of numbers into an array. Print how many of them are negative.Examples: 3 -1 -5 0 2 gives 21 2 3 gives 0-1 -2 -3 gives 3
    Show a hint
    a < 0 is a mask, and sum counts its True values: (a < 0).sum().
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print((a < 0).sum())

    Output

    2
  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
    Python
    import numpy as np
    
    table = np.arange(1, 21).reshape(4, 5)
    print(table[:2, -2:])

    Output

    [[ 4  5]
     [ 9 10]]
  3. 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 49 gives ['pass' 'fail' 'pass' 'fail']50 gives ['pass']49 gives ['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
    Python
    import numpy as np
    
    grades = np.array(list(map(int, input().split())))
    print(np.where(grades >= 50, "pass", "fail"))

    Output

    ['pass' 'fail' 'pass' 'fail']
  4. 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 5 gives [4 5]10 10 10 gives []5 gives []
    Show a hint
    a.mean() is one number, so a > a.mean() is a mask. Use it inside the brackets.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a[a > a.mean()])

    Output

    [4 5]
  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 is axis=1. One result for every column is axis=0.
    Show one possible solution
    Python
    import 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.

  1. 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 99 gives [ 50 100 100 100 99]1 2 3 gives [1 2 3]200 gives [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
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    a[a > 100] = 100
    print(a)

    Output

    [ 50 100 100 100  99]
  2. 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 25 gives [10 15 20]9 21 gives []10 gives [10]
    Show a hint
    Two conditions joined with &, each in its own parentheses: (a >= 10) & (a <= 20).
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a[(a >= 10) & (a <= 20)])

    Output

    [10 15 20]
  3. 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 4 gives 1605, 3 gives 151 1 1, 0 0 0 gives 0
    Show a hint
    prices * amounts multiplies element by element: the cost of every product. Then add the costs up with .sum().
    Show one possible solution
    Python
    import 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
  4. 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 with np.round(averages, 1). The index of the highest one is averages.argmax().
    Show one possible solution
    Python
    import 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
  5. 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 30 gives [0. 0.5 1. ]0 5 10 20 gives [0. 0.25 0.5 1. ]3 1 2 gives [1. 0. 0.5]
    Show a hint
    Store a.min() and a.max() first. Then one line on the whole array: (a - smallest) / (largest - smallest).
    Show one possible solution
    Python
    import 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.

Question 1

1.What does this print?

a = np.array([10, 20, 30, 40, 50])
print(a[1:3])

Question 2

2.What does this print?

table = np.arange(1, 13).reshape(3, 4)
print(table[:, 0])

Question 3

3.What does this print?

table = np.arange(1, 13).reshape(3, 4)
print(table[1:, :2].shape)

Question 4

4.What does this print?

a = np.array([1, 2, 3, 4])
b = a[:2]
b[0] = 9
print(a)

Question 5

5.What does this print?

numbers = [1, 2, 3]
print(numbers * 2, np.array(numbers) * 2)

Question 6

6.What does this print?

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print((a * b).sum())

Question 7

7.What does this print?

grades = np.array([55, 80, 42, 90])
print((grades >= 60).sum())

Question 8

8.What does this print?

a = np.array([1, 2, 3, 4, 5, 6])
print(a[(a > 2) & (a < 5)])

Question 9

9.Which line prints the grades that are at least 60 and below 90?

Question 10

10.What does this print?

a = np.array([5, -3, 8])
print(np.where(a < 0, 0, a))

Question 11

11.What does this print?

t = np.array([[1, 2, 3], [4, 5, 6]])
print(t.sum(axis=0))

Question 12

12.table has the shape (2, 3). Which of these can NOT be added to it?

0 of 12 answered.

13Quick summary

Quick summary
ConceptWhat it doesExample
1D slicea part of an arraya[1:4], a[::-1]
2D slicerows, then columnstable[0:2, 1:3]
: aloneall rows or all columnstable[:, 1]
Viewa slice shares its data with the originalpart = a[1:4]
copya separate arraya[1:4].copy()
Vectorized operationa calculation on every element, no loopprices * 2, a + b
np.sqrt, np.abs, np.roundmath on every elementnp.round(c, 1)
Comparisonan array of True and Falsegrades >= 60
Maskchooses the elements where it is Truegrades[grades >= 60]
&, |, ~and, or, not for masks(a > 2) & (a < 5)
np.wherethis value or that valuenp.where(a > 0, a, 0)
axis=0 / axis=1one result for every column / every rowtable.sum(axis=0)
np.sorta sorted copynp.sort(a)
Broadcastinga smaller shape is stretched to fittable + row