Module 1, topic 8, week 4, Thursday
NumPy fundamentals: arrays and indexing
Creating arrays, their shape and data type, reaching elements by index in one and two dimensions, and reshape
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-08-numpy-arrays-indexing.ipynb, 50 KB
Practice notebook
The 15 practice problems with a hint and a hidden solution for each.
topic-08-practice.ipynb, 26 KB
Introduction: NumPy arrays and indexing
A beginner-friendly guide to NumPy, the library that almost all Data Science in Python is built on. It starts from the simplest examples and gets harder step by step: what an array is and how it differs from a list, how to create arrays, what their properties and data types are, and how to reach and change single elements with indexes in one and two dimensions. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know lists, loops, functions and how to import a module.
This lesson and the next one. This lesson is about creating arrays and reaching elements by index. The next lesson continues with slicing, broadcasting and calculations on whole arrays without loops. Those topics are left out here on purpose.
What you will learn
- 1.What NumPy is, how to import it, and how an array differs from a list
- 2.Creating arrays from lists, and with
zeros,ones,full,arange,linspace - 3.The properties
ndim,shape,sizeanddtype - 4.Data types of arrays, and converting with
astype - 5.Indexing a 1D array and a 2D array, and changing elements
- 6.Taking several elements at once with a list of indexes
- 7.Changing the shape with
reshape - 8.Going through an array with loops, simple summaries, and copying an array
- 9.15 solved problems and practice problems
1NumPy and the first arrays
1.1What is NumPy?
NumPy (Numerical Python) is a package for working with numbers in arrays. An array is a grid of values, like a list or a table, but built for calculation. pandas, Matplotlib and scikit-learn all store their data in NumPy arrays, so everything in the rest of this course stands on it.
1.2Importing NumPy
NumPy is not part of Python itself. With Anaconda it is already installed. Everybody imports it with the short name np:
import numpy as np
print(np.__version__)Output
2.4.6
1.3The first array
np.array(...) turns a list into an array:
import numpy as np
grades = np.array([85, 92, 78, 60, 95])
print(grades)
print(type(grades))Output
[85 92 78 60 95] <class 'numpy.ndarray'>
Change it and run: add two more grades to the list.
Notice two things. The array is printed without commas. And its type is ndarray, which means "n-dimensional array".
1.4Why not just a list?
| List | NumPy array | |
|---|---|---|
| Types of the items | any mix | one type for all items |
| Made for | general collections | numbers and calculation |
| Dimensions | a list of lists for a table | real rows and columns |
| Size | can grow (append) | fixed when created |
| Speed with many numbers | slow | fast |
An array gives up flexibility (one type, fixed size) and gets speed and a clear shape in return.
1.5An array from a list: one dimension
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([2.5, 10.0, 7.25])
print(a)
print(b)Output
[1 2 3 4] [ 2.5 10. 7.25]
Change it and run: put your own numbers into a.
1.6An array from a list of lists: two dimensions
A list of lists becomes an array with rows and columns. Every inner list is one row:
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table)Output
[[1 2 3] [4 5 6]]
Change it and run: add a third row, [7, 8, 9].
All rows must have the same length. This is a real table, not just lists inside a list.
1.7The square brackets are required
np.array takes one list. Forgetting the brackets is a very common mistake:
import numpy as np
a = np.array(1, 2, 3)Error
TypeError: array() takes from 1 to 2 positional arguments but 3 were given
1.8One type for all items
If the list mixes whole numbers and decimals, NumPy converts everything to decimals:
import numpy as np
mixed = np.array([1, 2, 3.5])
print(mixed)Output
[1. 2. 3.5]
Change it and run: change 3.5 to 3. The dots disappear, because every item is a whole number now.
1. and 2. are the decimals 1.0 and 2.0. NumPy prints them in this short way.
If the list contains a text, everything becomes text. Calculations are then impossible:
import numpy as np
mixed = np.array([1, 2, "three"])
print(mixed)Output
['1' '2' 'three']
Change it and run: change "three" to 3. The quotes disappear.
1.9From an array back to a list
import numpy as np
a = np.array([1, 2, 3])
print(a.tolist())
print(type(a.tolist()))Output
[1, 2, 3] <class 'list'>
Try it yourself
[3, 6, 9, 12]. Print the array, then print it as a list again with tolist().Show a hint
a = np.array([3, 6, 9, 12]), then print(a) and print(a.tolist()). Compare the two lines: one has commas, the other has none.Show the solution
import numpy as np
a = np.array([3, 6, 9, 12])
print(a)
print(a.tolist())Output
[ 3 6 9 12] [3, 6, 9, 12]
2The properties of an array
Every array knows four things about itself:
| Property | Meaning | Example for a table with 2 rows and 3 columns |
|---|---|---|
ndim | the number of dimensions | 2 |
shape | the size in each dimension, as a tuple | (2, 3) |
size | the total number of items | 6 |
dtype | the data type of the items | int64 |
They are attributes, so they are written without parentheses.
import numpy as np
a = np.array([10, 20, 30, 40])
print(a.ndim)
print(a.shape)
print(a.size)
print(a.dtype)Output
1 (4,) 4 int64
Change it and run: add a fifth number to the list. Which of the four lines change?
(4,) is a tuple with one item: one dimension with 4 items.
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table.ndim)
print(table.shape)
print(table.size)
print(table.dtype)Output
2 (2, 3) 6 int64
Change it and run: add a third row, [7, 8, 9]. Predict shape and size before you run it.
How to read a shape: (2, 3) means 2 rows and 3 columns. Rows always come first.
One dimension
4 items
- ndim
- 1
- shape
- (4,)
- size
- 4
Two dimensions
3 columns
2 rows
- ndim
- 2
- shape
- (2, 3)
- size
- 6
2.1len gives the number of rows
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(len(table))
print(table.shape[0], table.shape[1])Output
2 2 3
Change it and run: add a third row and run it again.
For a 2D array, len is the number of rows, not the number of items. shape[0] is the number of rows and shape[1] the number of columns.
Try it yourself
shape, size and dtype, each on its own line.Show a hint
a.shape, a.size, a.dtype, without parentheses. On this page the last line shows int32, and that counts as right.Show the solution
import numpy as np
a = np.array([5, 10, 15, 20, 25])
print(a.shape)
print(a.size)
print(a.dtype)Output
(5,) 5 int64
3Ready-made arrays
Often you need an array of a certain size before you have the data.
3.1zeros, ones, full
import numpy as np
print(np.zeros(4))
print(np.ones(3))
print(np.full(5, 7))Output
[0. 0. 0. 0.] [1. 1. 1.] [7 7 7 7 7]
Change it and run: make 10 zeros, and an array of six 3s.
For two dimensions, give the shape as a tuple (rows, columns):
import numpy as np
print(np.zeros((2, 3)))
print(np.full((2, 2), 9))Output
[[0. 0. 0.] [0. 0. 0.]] [[9 9] [9 9]]
Change it and run: make a table of ones with 3 rows and 5 columns.
zeros and ones make decimals (0., 1.) unless you ask for another type (Part 4).
3.2arange: like range, but an array
import numpy as np
print(np.arange(5))
print(np.arange(2, 10))
print(np.arange(0, 20, 5))
print(np.arange(0, 1, 0.25))Output
[0 1 2 3 4] [2 3 4 5 6 7 8 9] [ 0 5 10 15] [0. 0.25 0.5 0.75]
Change it and run: print the even numbers from 0 to 20, with 20 included.
The rules are the same as for range: start, stop (not included), step. Unlike range, the step can be a decimal.
3.3linspace: a fixed number of evenly spaced values
import numpy as np
print(np.linspace(0, 1, 5))
print(np.linspace(0, 100, 3))Output
[0. 0.25 0.5 0.75 1. ] [ 0. 50. 100.]
Change it and run: change the count in the first line from 5 to 11.
linspace(start, stop, count) gives exactly count values, and the stop value is included.
| arange(start, stop, step) | linspace(start, stop, count) | |
|---|---|---|
| You choose | the step | how many values |
| Stop value | not included | included |
Move the sliders and watch where the values land.
np.arange(0, 20, 5)
4 values, one every 5. The stop, 20, is never one of them: the ring on the line marks it.
3.4eye: the identity matrix
import numpy as np
print(np.eye(3))Output
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
Change it and run: change 3 to 5.
Ones on the diagonal, zeros elsewhere. You will meet it again in linear algebra.
3.5Random numbers
Random arrays are used all the time, for test data and in machine learning. The values are different on every run, so the output is not shown here:
import numpy as np
print(np.random.randint(1, 7, 5)) # 5 whole numbers from 1 to 6
print(np.random.rand(3)) # 3 decimals between 0 and 1
print(np.random.rand(2, 3)) # 2 rows, 3 columnsChange it and run: run it several times. The numbers are different each time.
| Function | What it makes | Example |
|---|---|---|
np.array(list) | an array from a list | np.array([1, 2, 3]) |
np.zeros(shape) | all zeros | np.zeros((2, 3)) |
np.ones(shape) | all ones | np.ones(4) |
np.full(shape, value) | one value everywhere | np.full(5, 7) |
np.arange(start, stop, step) | numbers with a step | np.arange(0, 20, 5) |
np.linspace(start, stop, count) | a number of evenly spaced values | np.linspace(0, 1, 5) |
np.eye(n) | the identity matrix | np.eye(3) |
np.random.randint(low, high, count) | random whole numbers | np.random.randint(1, 7, 5) |
Try it yourself
linspace and print them.Show a hint
np.linspace(start, stop, count): the start is 0, the stop is 10 and the count is 5.Show the solution
import numpy as np
print(np.linspace(0, 10, 5))Output
[ 0. 2.5 5. 7.5 10. ]
4Data types
All items of an array have the same type, called the dtype.
| dtype | Meaning | Example |
|---|---|---|
int64 | whole numbers | np.array([1, 2, 3]) |
float64 | decimals | np.array([1.5, 2.0]) |
bool | True and False | np.array([True, False]) |
<U... | text | np.array(["a", "b"]) |
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1.5, 2.0]).dtype)
print(np.array([True, False]).dtype)
print(np.array(["red", "green"]).dtype)Output
int64 float64 bool <U5
<U5 means text with up to 5 characters. The number 64 in int64 is the size of each number in memory, in bits.
4.1Choosing the type: dtype=
import numpy as np
a = np.array([1, 2, 3], dtype=float)
b = np.zeros(3, dtype=int)
print(a)
print(b)Output
[1. 2. 3.] [0 0 0]
Change it and run: change dtype=float to dtype=str.
4.2Converting: astype
astype makes a new array with another type:
import numpy as np
prices = np.array([2.9, 10.5, 7.1])
whole = prices.astype(int)
print(whole)
print(prices)
texts = np.array(["10", "20", "30"])
numbers = texts.astype(int)
print(numbers)
print(numbers.dtype)Output
[ 2 10 7] [ 2.9 10.5 7.1] [10 20 30] int64
Change it and run: change 2.9 to -2.9. The result is -2, not -3: the decimal part is cut off.
Converting decimals to int cuts off the decimal part. It does not round. The original array is not changed.
4.3A trap: a decimal stored in an array of whole numbers
import numpy as np
a = np.array([1, 2, 3])
a[0] = 9.9
print(a)Output
[9 2 3]
Change it and run: add dtype=float to the first line: np.array([1, 2, 3], dtype=float).
The array has the type int64, so 9.9 was cut to 9 without any warning. If you need decimals, create the array with dtype=float.
4.4One element is a NumPy number
One element of an array is not a Python int. It is a NumPy number with the type of the array:
import numpy as np
a = np.array([10, 20, 30])
print(a[0] + 5)
print(type(a[0]))
print([a[0], a[1]])
print(a.tolist())Output
15 <class 'numpy.int64'> [np.int64(10), np.int64(20)] [10, 20, 30]
Change it and run: change the list to [1.5, 2.5, 3.5] and look at the type again.
It calculates and prints like a normal number. Only inside a list, a tuple or a dictionary does Python show its full name, np.int64(10). When you need plain Python numbers, use a.tolist() for the whole array, or int(a[0]) for one element.
Try it yourself
[2.7, 3.2, 9.9], convert it to whole numbers with astype, and print both arrays: first the original one, then the new one.Show a hint
whole = a.astype(int) makes a new array and leaves a as it is. Is 9.9 rounded to 10?Show the solution
import numpy as np
a = np.array([2.7, 3.2, 9.9])
whole = a.astype(int)
print(a)
print(whole)Output
[2.7 3.2 9.9] [2 3 9]
5Indexing: one element
5.1Indexing a 1D array
Indexing works as with lists: square brackets, and counting starts at 0.
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| value | 10 | 20 | 30 | 40 | 50 |
| negative | -5 | -4 | -3 | -2 | -1 |
a[-1] is always the last element.import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0])
print(a[2])
print(a[-1])
print(a[-2])Output
10 30 50 40
Change it and run: print the element 30 in two ways: with a positive and with a negative index.
An index that does not exist is an error:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[5])Error
IndexError: index 5 is out of bounds for axis 0 with size 5
"Axis 0" is the first (and here the only) dimension.
5.2Changing an element
Arrays are mutable, like lists:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
a[0] = 99
a[-1] = a[-1] + 1
print(a)Output
[99 20 30 40 51]
Change it and run: set the middle element to 0.
5.3The size is fixed
An array has no append method. Its size is set when it is created:
import numpy as np
a = np.array([10, 20, 30])
a.append(40)Error
AttributeError: 'numpy.ndarray' object has no attribute 'append'
np.append(a, 40) exists, but it builds a new array each time. Collect values in a list first, and convert the list to an array at the end.
5.4Indexing a 2D array
A 2D array needs two indexes: the row, then the column, separated by a comma.
| column 0 | column 1 | column 2 | |
|---|---|---|---|
| row 0 | 1 | 2 | 3 |
| row 1 | 4 | 5 | 6 |
| row 2 | 7 | 8 | 9 |
table[1, 2]: go down to row 1, then across to column 2. The element where they cross is 6.import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table[0, 0])
print(table[1, 2])
print(table[2, 0])
print(table[-1, -1])Output
1 6 7 9
Change it and run: print the 8, then the 6.
table[1, 2] means: row 1, column 2. Row first, then column.
Press an element, or press a row name to take the whole row.
| column 0 | column 1 | column 2 | |
|---|---|---|---|
print(table[1, 2])
Result: 6
Row 1 first, then column 2. With negative indexes the same element is table[-2, -1].
5.5One index gives a whole row
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table[0])
print(table[-1])
print(table[1].shape)Output
[1 2 3] [7 8 9] (3,)
Change it and run: print the middle row.
A row of a 2D array is a 1D array.
5.6table[1, 2] or table[1][2]?
Both give the same element. The first form is the NumPy way: it is shorter, and it is the form that the next lesson builds on.
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table[1, 2])
print(table[1][2])Output
6 6
5.7Changing elements and whole rows
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
table[0, 0] = 100
table[2] = [0, 0, 0]
print(table)Output
[[100 2 3] [ 4 5 6] [ 0 0 0]]
Change it and run: change the 5 in the middle to 0.
5.8An index out of range
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table[0, 3])Error
IndexError: index 3 is out of bounds for axis 1 with size 3
The message tells you which axis is wrong: axis 0 is the rows, axis 1 is the columns.
| You write | You get |
|---|---|
table[1, 2] | one element: row 1, column 2 |
table[1] | the whole row 1, as a 1D array |
table[-1, -1] | the last element of the last row |
table[1, 2] = 0 | changes one element |
table[1] = [0, 0, 0] | changes a whole row |
Try it yourself
table, print the element 6, then the whole last row. Then set the element in row 0, column 1 to 0 and print the table.Show a hint
table[1, 2]. The last row is table[-1]. Changing one element: table[0, 1] = 0.Show the solution
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table[1, 2])
print(table[-1])
table[0, 1] = 0
print(table)Output
6 [7 8 9] [[1 0 3] [4 5 6] [7 8 9]]
6Several elements at once: a list of indexes
Instead of one index you can give a list of indexes. The result is a new array with those elements, in the order you asked for:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[[0, 2, 4]])
print(a[[4, 0]])
print(a[[1, 1, 1]])Output
[10 30 50] [50 10] [20 20 20]
Change it and run: print 50, 30, 10, in this order.
Notice the double brackets: the outer ones are the indexing, the inner ones are the list.
Press the elements in any order. Each press adds its index to the list.
| 0 | 1 | 2 | 3 | 4 |
a = np.array([10, 20, 30, 40, 50]) print(a[[0, 2, 4]])
Result: [10 30 50]
The result has one element for each index, in the order of the list. An index can appear more than once, and an empty list gives an empty array.
The list can be stored in a variable, or be another array:
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran"])
winners = [2, 0]
print(names[winners])Output
['Leyla' 'Aylin']
Change it and run: change winners to [3, 1, 0].
6.1Rows of a 2D array
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table[[0, 2]])Output
[[1 2 3] [7 8 9]]
Change it and run: print the rows in the opposite order: the last, the middle, the first.
6.2Chosen elements of a 2D array
With two lists, NumPy takes them in pairs: the first row index with the first column index, and so on.
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(table[[0, 1, 2], [0, 1, 2]])
print(table[[0, 2], [2, 0]])Output
[1 5 9] [3 7]
Change it and run: take the other diagonal: 3, 5, 7.
The first line takes the elements at (0, 0), (1, 1) and (2, 2): the diagonal.
table[[0, 2], [2, 0]]
| rows | 0 | 2 |
|---|---|---|
| columns | 2 | 0 |
| pair | (0, 2) | (2, 0) |
| element | 3 | 7 |
| column 0 | column 1 | column 2 | |
|---|---|---|---|
| row 0 | 1 | 2 | 3 |
| row 1 | 4 | 5 | 6 |
| row 2 | 7 | 8 | 9 |
[3 7].6.3Changing several elements
import numpy as np
a = np.array([10, 20, 30, 40, 50])
a[[0, 4]] = 0
print(a)Output
[ 0 20 30 40 0]
Change it and run: set the elements 20 and 40 to -1.
Try it yourself
prices, print the prices at the indexes 1, 3 and 4 as one array. Then set the first and the last price to 0 and print the array.Show a hint
prices[[1, 3, 4]] takes three elements. prices[[0, -1]] = 0 changes two elements at once.Show the solution
import numpy as np
prices = np.array([4.5, 12.0, 7.25, 3.0, 9.5])
print(prices[[1, 3, 4]])
prices[[0, -1]] = 0
print(prices)Output
[12. 3. 9.5] [ 0. 12. 7.25 3. 0. ]
7Changing the shape: reshape
reshape arranges the same items in another shape. The number of items must stay the same.
import numpy as np
a = np.arange(1, 7)
print(a)
table = a.reshape(2, 3)
print(table)
print(table.shape)Output
[1 2 3 4 5 6] [[1 2 3] [4 5 6]] (2, 3)
Change it and run: reshape to 1 row and 6 columns, then to 6 rows and 1 column.
The items fill the new shape row by row.
import numpy as np
a = np.arange(1, 7)
print(a.reshape(3, 2))Output
[[1 2] [3 4] [5 6]]
7.1-1: let NumPy calculate one size
import numpy as np
a = np.arange(12)
print(a.reshape(3, -1))
print(a.reshape(-1, 6).shape)Output
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] (2, 6)
Change it and run: change reshape(3, -1) to reshape(2, -1), then to reshape(5, -1). The last one fails: 12 items cannot fill 5 equal rows.
-1 means "whatever fits". With 12 items and 3 rows, NumPy finds 4 columns.
7.2The sizes must match
import numpy as np
a = np.arange(6)
print(a.reshape(4, 2))Error
ValueError: cannot reshape array of size 6 into shape (4,2)
Choose the rows and the columns for the 12 items.
a = np.arange(1, 13) print(a.reshape(3, 4))
3 × 4 = 12, so it fits. The shape is (3, 4), and the items fill it row by row.
7.3Back to one dimension: flatten
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table.flatten())Output
[1 2 3 4 5 6]
arange and reshape together are the quickest way to make a test table:
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table)
print(table[2, 1])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] 10
Change it and run: make a table with 4 rows and 3 columns from the same numbers.
Try it yourself
arange and reshape them into 2 rows. Let NumPy find the number of columns with -1. Print the table and its shape.Show a hint
np.arange(10, 90, 10) stops before 90. Then .reshape(2, -1).Show the solution
import numpy as np
a = np.arange(10, 90, 10)
table = a.reshape(2, -1)
print(table)
print(table.shape)Output
[[10 20 30 40] [50 60 70 80]] (2, 4)
8Loops, summaries and copying
8.1A loop over a 1D array
import numpy as np
grades = np.array([85, 42, 78, 60])
for grade in grades:
if grade >= 50:
print(grade, "passed")
else:
print(grade, "failed")Output
85 passed 42 failed 78 passed 60 passed
Change it and run: change the pass mark from 50 to 80.
8.2A loop over a 2D array gives the rows
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
for row in table:
print(row, "first item:", row[0])Output
[1 2 3] first item: 1 [4 5 6] first item: 4
Change it and run: print the last item of each row instead.
8.3Every element with its indexes
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
for i in range(table.shape[0]):
for j in range(table.shape[1]):
print(i, j, table[i, j])Output
0 0 1 0 1 2 0 2 3 1 0 4 1 1 5 1 2 6
Change it and run: add a third row to the table. The loops need no change.
shape[0] rows and shape[1] columns give the two ranges.
(In the next lesson you will see that most calculations on arrays need no loop at all. Loops are shown here because they make the indexes visible.)
8.4Simple summaries
An array can summarise itself:
import numpy as np
grades = np.array([85, 92, 78, 60, 95])
print(grades.sum())
print(grades.mean())
print(grades.min(), grades.max())Output
410 82.0 60 95
Change it and run: add the grade 0 to the array. Which results change?
argmax and argmin give the index of the largest and the smallest element. With the index you can look into another array:
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran", "Nigar"])
grades = np.array([85, 92, 78, 60, 95])
best = grades.argmax()
print(best)
print(names[best], grades[best])
print(names[grades.argmin()])Output
4 Nigar 95 Kamran
Change it and run: change Murad's grade to 99.
| index | grades | names |
|---|---|---|
| 0 | 85 | Aylin |
| 1 | 92 | Murad |
| 2 | 78 | Leyla |
| 3 | 60 | Kamran |
| 4 | 95 | Nigar |
grades.argmax() is 4: the position of the largest grade, not the grade itself. The same position in names is the student.8.5Copying an array
As with lists, b = a does not copy. It gives the same array a second name:
import numpy as np
a = np.array([1, 2, 3])
b = a
b[0] = 100
print(a)Output
[100 2 3]
.copy() makes a real, separate array:
import numpy as np
a = np.array([1, 2, 3])
b = a.copy()
b[0] = 100
print(a)
print(b)Output
[1 2 3] [100 2 3]
Change it and run: change b = a.copy() back to b = a and compare.
Try it yourself
temps, print the mean temperature. Then print the name of the warmest day and the name of the coldest day, each on its own line.Show a hint
temps.mean() is the mean. temps.argmax() is the index of the warmest day: use it in days. argmin does the same for the coldest day.Show the solution
import numpy as np
days = np.array(["Mon", "Tue", "Wed", "Thu", "Fri"])
temps = np.array([18, 22, 25, 19, 16])
print(temps.mean())
print(days[temps.argmax()])
print(days[temps.argmin()])Output
20.0 Wed Fri
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.
np.array(1, 2, 3) without the square brackets
Wrong
import numpy as np a = np.array(1, 2, 3)
TypeError: array() takes from 1 to 2 positional arguments but 3 were given
Right
import numpy as np a = np.array([1, 2, 3]) print(a) # prints: [1 2 3]
TypeError. np.array takes one list: np.array([1, 2, 3]).
Forgetting import numpy as np
Wrong
a = np.array([1, 2, 3]) print(a)
NameError: name 'np' is not defined
Right
import numpy as np a = np.array([1, 2, 3]) print(a) # prints: [1 2 3]
NameError: name 'np' is not defined. Import it at the top.
a.shape() with parentheses
Wrong
import numpy as np a = np.array([1, 2, 3]) print(a.shape())
TypeError: 'tuple' object is not callable
Right
import numpy as np a = np.array([1, 2, 3]) print(a.shape) # prints: (3,)
TypeError: a tuple is not callable. a.shape is an attribute.
np.zeros(2, 3)
Wrong
import numpy as np print(np.zeros(2, 3))
TypeError: Cannot interpret '3' as a data type
Right
import numpy as np print(np.zeros((2, 3))) print(np.full((2, 2), 9)) # prints: [[0. 0. 0.], [0. 0. 0.]], [[9 9], [9 9]]
TypeError. The shape is one tuple: np.zeros((2, 3)).
Rows of different lengths
Wrong
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5],
])ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
Right
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table)
# prints: [[1 2 3], [4 5 6]]ValueError. Every row needs the same number of items.
Index out of range
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[5])
IndexError: index 5 is out of bounds for axis 0 with size 5
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[a.size - 1]) print(a[-1]) # prints: 50, 50
IndexError. The last index is size - 1, or use -1.
Column first, then row
Wrong
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table[2, 1])IndexError: index 2 is out of bounds for axis 0 with size 2
Right
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
])
print(table[1, 2])
# prints: 6The wrong element, or IndexError. Row first: table[row, column].
a.append(x)
Wrong
import numpy as np a = np.array([10, 20, 30]) a.append(40)
AttributeError: 'numpy.ndarray' object has no attribute 'append'
Right
import numpy as np values = [10, 20, 30] values.append(40) a = np.array(values) print(a) # prints: [10 20 30 40]
AttributeError. Arrays have a fixed size: build a list first.
A decimal stored in an int array
Wrong
import numpy as np a = np.array([1, 2, 3]) a[0] = 9.9 print(a) # prints: [9 2 3]
Right
import numpy as np a = np.array([1, 2, 3], dtype=float) a[0] = 9.9 print(a) # prints: [9.9 2. 3. ]
The decimal part is cut off silently. Create the array with dtype=float.
reshape to a shape that does not fit
Wrong
import numpy as np a = np.arange(6) print(a.reshape(4, 2))
ValueError: cannot reshape array of size 6 into shape (4,2)
Right
import numpy as np a = np.arange(1, 7) print(a.reshape(3, 2)) # prints: [[1 2], [3 4], [5 6]]
ValueError. Rows × columns must equal size.
b = a to copy
Wrong
import numpy as np a = np.array([1, 2, 3]) b = a b[0] = 100 print(a) # prints: [100 2 3]
Right
import numpy as np a = np.array([1, 2, 3]) b = a.copy() b[0] = 100 print(a) print(b) # prints: [1 2 3], [100 2 3]
Both names change together. Use b = a.copy().
a[0, 2, 4] for several elements
Wrong
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[0, 2, 4])
IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
Right
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[[0, 2, 4]]) print(a[[4, 0]]) print(a[[1, 1, 1]]) # prints: [10 30 50], [50 10], [20 20 20]
IndexError: too many indices. A list inside: a[[0, 2, 4]].
shape with parentheses:
import numpy as np
a = np.array([1, 2, 3])
print(a.shape())Error
TypeError: 'tuple' object is not callable
Rows of different lengths:
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5],
])Error
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
Several elements without the inner list:
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0, 2, 4])Error
IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
10Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
10.1Level 1: Easy
Problem 1: Create an array and look at it
import numpy as np
a = np.array([4, 8, 15, 16, 23, 42])
print(a)
print(a.shape, a.size, a.dtype)Output
[ 4 8 15 16 23 42] (6,) 6 int64
Problem 2: First, last and middle element
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0])
print(a[-1])
print(a[a.size // 2])Output
10 50 30
Change it and run: add a sixth number, 60. Which element is the middle one now?
Problem 3: The numbers from 1 to 10
import numpy as np
a = np.arange(1, 11)
print(a)
print(a.sum())Output
[ 1 2 3 4 5 6 7 8 9 10] 55
Change it and run: make the numbers from 1 to 100 and print their sum.
Problem 4: A table of zeros with one value changed
import numpy as np
table = np.zeros((3, 4), dtype=int)
table[1, 2] = 5
print(table)Output
[[0 0 0 0] [0 0 5 0] [0 0 0 0]]
Change it and run: set the four corners of the table to 1.
Problem 5: One element of a table
import numpy as np
table = np.array([
[5, 10, 15],
[20, 25, 30],
])
print(table[0, 1])
print(table[1, -1])
print(table.shape)Output
10 30 (2, 3)
Change it and run: print the 25.
10.2Level 2: Medium
Problem 6: An array from user input
import numpy as np
numbers = np.array(list(map(int, input().split())))
print(numbers)
print(numbers.size, numbers.sum(), numbers.max())Output
4 8 15 16 [ 4 8 15 16] 4 43 16
Change it and run: run it with other numbers, for example 3 9 2.
Why: the input line becomes a list of numbers (as in the lesson about lists), and np.array turns the list into an array.
Problem 7: The four corners of a table
import numpy as np
table = np.arange(1, 13).reshape(3, 4)
print(table)
print(table[0, 0], table[0, -1], table[-1, 0], table[-1, -1])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] 1 4 9 12
Change it and run: change the shape to reshape(4, 3). The same line still prints the corners.
Why: negative indexes work in each dimension, so the corners need no knowledge of the size.
Problem 8: The best student
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran"])
grades = np.array([85, 92, 78, 45])
best = grades.argmax()
print(names[best], grades[best])
print("Average:", grades.mean())Output
Murad 92 Average: 75.0
Change it and run: change Kamran's grade to 99.
Why: argmax gives a position, and the same position is used in both arrays.
Problem 9: Chosen students
import numpy as np
names = np.array(["Aylin", "Murad", "Leyla", "Kamran", "Nigar"])
grades = np.array([85, 92, 78, 45, 66])
chosen = [0, 2, 4]
print(names[chosen])
print(grades[chosen])
print(grades[chosen].mean())Output
['Aylin' 'Leyla' 'Nigar'] [85 78 66] 76.33333333333333
Change it and run: choose the students at the indexes 1 and 3.
Problem 10: Decimals to whole numbers
import numpy as np
prices = np.array([2.9, 10.5, 7.1, 3.99])
whole = prices.astype(int)
print(whole)
print(whole.dtype)
print(prices.sum(), whole.sum())Output
[ 2 10 7 3] int64 24.490000000000002 22
Why: astype(int) cuts off the decimals, so the sum of the whole numbers is smaller.
10.3Level 3: Medium-Hard
Problem 11: The sum of every row, with loops
import numpy as np
table = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
for i in range(table.shape[0]):
total = 0
for j in range(table.shape[1]):
total = total + table[i, j]
print("Row", i, "sum:", total)Output
Row 0 sum: 6 Row 1 sum: 15 Row 2 sum: 24
Change it and run: add a fourth row, [10, 11, 12].
Why: two loops, one for the rows and one for the columns, and table[i, j] reaches each element. (The next lesson does this in one line.)
Problem 12: The diagonal of a square table
import numpy as np
table = np.arange(1, 17).reshape(4, 4)
print(table)
positions = list(range(4))
print(table[positions, positions])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] [ 1 6 11 16]
Change it and run: print the other diagonal (4, 7, 10, 13). The columns are then [3, 2, 1, 0].
Why: the diagonal elements are (0, 0), (1, 1), (2, 2), (3, 3). Two equal lists of indexes take them in pairs.
Problem 13: Swap the first and the last row
import numpy as np
table = np.arange(1, 10).reshape(3, 3)
table[[0, -1]] = table[[-1, 0]]
print(table)Output
[[7 8 9] [4 5 6] [1 2 3]]
Change it and run: swap the first and the middle row.
Why: the right side takes the rows in the order (last, first), and the left side stores them at (first, last).
Problem 14: Count the even numbers in a table
import numpy as np
table = np.array([
[3, 8, 5],
[12, 7, 10],
])
count = 0
for row in table:
for value in row:
if value % 2 == 0:
count = count + 1
print("Even numbers:", count)Output
Even numbers: 3
Change it and run: count the odd numbers instead.
Problem 15: A grade table
Each row is a student, each column an exam. Print the best exam of every student.
import numpy as np
names = ["Aylin", "Murad", "Leyla"]
grades = np.array([
[85, 90, 78],
[92, 60, 88],
[70, 75, 95],
])
for i in range(len(names)):
row = grades[i]
best = row.argmax()
print(names[i], "- best exam:", best + 1, "with", row[best])Output
Aylin - best exam: 2 with 90 Murad - best exam: 1 with 92 Leyla - best exam: 3 with 95
Change it and run: change one of Murad's grades to 100.
Why: grades[i] is the row of one student. argmax gives the position of the best grade in that row, and + 1 turns the index into an exam number.
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
Creating an array, its properties, and one element.
- 1.Create an array with the numbers from 0 to 9 using
arange, and print the first and the last element on one line.Show a hint
np.arange(10)stops before 10. The first element isa[0]and the last one isa[-1]. Oneprintwith a comma puts both on one line.Show one possible solution
Pythonimport numpy as np a = np.arange(10) print(a[0], a[-1])Output
0 9
- 2.Create an array of 6 zeros with the type
int. Change the element at index 2 to 7 and print the array.Show a hint
np.zeros(6, dtype=int)makes whole numbers. Thena[2] = 7.Show one possible solution
Pythonimport numpy as np a = np.zeros(6, dtype=int) a[2] = 7 print(a)Output
[0 0 7 0 0 0]
- 3.Read a line of numbers and turn it into an array. Print the array and its largest element on one line.Examples:
4 8 15 16gives[ 4 8 15 16] 167gives[7] 7-3 -9 -1gives[-3 -9 -1] -1Show a hint
np.array(numbers)turns the list into an array. The largest element isa.max(). Print both with oneprint(a, a.max()).Show one possible solution
Pythonimport numpy as np numbers = list(map(int, input().split())) a = np.array(numbers) print(a, a.max())Output
[ 4 8 15 16] 16
- 4.Create the array
[[1, 2], [3, 4], [5, 6]]and print itsshape, its number of rows and the element in row 2, column 1, each on its own line.Show a hint
len(table)ortable.shape[0]is the number of rows. Row 2, column 1 istable[2, 1]: counting starts at 0.Show one possible solution
Pythonimport numpy as np table = np.array([[1, 2], [3, 4], [5, 6]]) print(table.shape) print(len(table)) print(table[2, 1])Output
(3, 2) 3 6
Medium
reshape, argmin, a list of indexes and the diagonal.
- 5.Create the numbers 1 to 12 and reshape them into 3 rows and 4 columns. Print the table and the element in the last row and the last column.
Show a hint
np.arange(1, 13)gives 1 to 12. Then.reshape(3, 4). The last row and the last column:table[-1, -1].Show one possible solution
Pythonimport numpy as np table = np.arange(1, 13).reshape(3, 4) print(table) print(table[-1, -1])Output
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] 12
- 6.Read a line of numbers into an array. Print the element in the middle (for an even size, the one right after the middle).Examples:
10 20 30 40 50gives3010 20 30 40gives307gives7Show a hint
The middle index isa.size // 2. For 5 elements that is index 2, for 4 elements it is also index 2.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) print(a[a.size // 2])Output
30
- 7.Given
names = np.array(["Aylin", "Murad", "Leyla", "Kamran"])andgrades = np.array([85, 92, 78, 45]), print the name of the student with the lowest grade.Show a hint
grades.argmin()gives the index of the lowest grade. Use the same index innames.Show one possible solution
Pythonimport numpy as np names = np.array(["Aylin", "Murad", "Leyla", "Kamran"]) grades = np.array([85, 92, 78, 45]) print(names[grades.argmin()])Output
Kamran
- 8.Read a line of numbers into an array and a line of indexes. Print the elements at those indexes, as an array.Examples:
10 20 30 40 50, 0 2 4gives[10 30 50]10 20 30 40 50, 4 0gives[50 10]Show a hint
A list of indexes goes inside the brackets:a[indexes]. Hereindexesalready is a list, so no extra brackets are needed.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) indexes = list(map(int, input().split())) print(a[indexes])Output
[10 30 50]
- 9.Create a 3 by 3 table of zeros (type
int) and set the three elements of its diagonal to 1 with indexes. Print the table.Show a hint
The diagonal elements are (0, 0), (1, 1) and (2, 2). Three lines liketable[0, 0] = 1work, and so does one line with two lists:table[[0, 1, 2], [0, 1, 2]] = 1.Show one possible solution
Pythonimport numpy as np table = np.zeros((3, 3), dtype=int) table[[0, 1, 2], [0, 1, 2]] = 1 print(table)Output
[[1 0 0] [0 1 0] [0 0 1]]
Medium-Hard
Loops with two indexes, pairs of indexes and a function.
- 10.Create the numbers 1 to 20 reshaped into 4 rows and 5 columns. With two loops and indexes, print the sum of every column, one line for each column, like
Column 0 sum: 34.Show a hint
The outer loop goes over the columns:for j in range(table.shape[1]). Inside it, starttotal = 0and addtable[i, j]for every rowi. Print withprint("Column", j, "sum:", total).Show one possible solution
Pythonimport numpy as np table = np.arange(1, 21).reshape(4, 5) for j in range(table.shape[1]): total = 0 for i in range(table.shape[0]): total = total + table[i, j] print("Column", j, "sum:", total)Output
Column 0 sum: 34 Column 1 sum: 38 Column 2 sum: 42 Column 3 sum: 46 Column 4 sum: 50
- 11.Read a line of numbers into an array. With a loop, count how many elements are larger than the mean of the array, and print the count.Examples:
1 2 3 4 5gives210 10 10gives05gives0Show a hint
Storea.mean()in a variable first. Then loop over the array and add 1 to a counter for every value that is larger.Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) mean = a.mean() count = 0 for value in a: if value > mean: count = count + 1 print(count)Output
2
- 12.Create a 4 by 4 table from the numbers 1 to 16. Print its four corner elements as one array, using two lists of indexes.
Show a hint
The corners are (0, 0), (0, -1), (-1, 0) and (-1, -1). The first list holds the four row indexes, the second one the four column indexes:table[[0, 0, -1, -1], [0, -1, 0, -1]].Show one possible solution
Pythonimport numpy as np table = np.arange(1, 17).reshape(4, 4) print(table[[0, 0, -1, -1], [0, -1, 0, -1]])Output
[ 1 4 13 16]
- 13.Read a line of 6 numbers and reshape them into 2 rows and 3 columns. Swap the two rows. The last line, which is already there, prints both rows on one line.Examples:
1 2 3 4 5 6gives[4 5 6] [1 2 3]7 7 7 0 0 0gives[0 0 0] [7 7 7]Show a hint
table = a.reshape(2, 3). Then swap with two lists of rows, as in solved problem 13:table[[0, 1]] = table[[1, 0]].Show one possible solution
Pythonimport numpy as np a = np.array(list(map(int, input().split()))) table = a.reshape(2, 3) table[[0, 1]] = table[[1, 0]] print(table[0], table[1])Output
[4 5 6] [1 2 3]
- 14.Write a function
largest_position(table)that returns the row index and the column index of the largest element of a 2D array. Use loops and indexes. If the largest value appears more than once, return its first position, reading row by row. The input is the number of rows and columns, then the numbers of the table.Examples:2 3, 3 8 5 12 7 10gives1 03 3, 1 2 3 4 5 6 7 8 9gives2 2Show a hint
Keep the best position in two variables that start at0, 0. Go through everyiandjwith two loops, and whentable[i, j]is larger than the element at the best position, storeiandj. Return both:return best_row, best_column.Show one possible solution
Pythonimport numpy as np def largest_position(table): best_row, best_column = 0, 0 for i in range(table.shape[0]): for j in range(table.shape[1]): if table[i, j] > table[best_row, best_column]: best_row, best_column = i, j return best_row, best_column rows, columns = map(int, input().split()) table = np.array(list(map(int, input().split()))).reshape(rows, columns) row, column = largest_position(table) print(row, column)Output
1 0
- 15.Given a grade table where each row is a student and each column an exam, print for every exam the index of the student with the best grade. Use loops and indexes. Print one line for each exam, like
Exam 0 best student: 1.Show a hint
The outer loop goes over the exams (columns). Inside it, start withbest = 0and comparegrades[i, j]withgrades[best, j]for every studenti. Print withprint("Exam", j, "best student:", best).Show one possible solution
Pythonimport numpy as np grades = np.array([ [85, 90, 78], [92, 60, 88], [70, 75, 95], ]) for j in range(grades.shape[1]): best = 0 for i in range(grades.shape[0]): if grades[i, j] > grades[best, j]: best = i print("Exam", j, "best student:", best)Output
Exam 0 best student: 1 Exam 1 best student: 0 Exam 2 best student: 2
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 |
|---|---|---|
import numpy as np | loads NumPy | np.array([1, 2, 3]) |
| Array | a grid of values of one type | np.array([[1, 2], [3, 4]]) |
ndim / shape / size | dimensions / size per dimension / number of items | table.shape gives (2, 3) |
dtype | the type of the items | int64, float64 |
zeros / ones / full | arrays filled with one value | np.zeros((2, 3)) |
arange | numbers with a step | np.arange(0, 20, 5) |
linspace | a number of evenly spaced values | np.linspace(0, 1, 5) |
astype | a new array with another type | prices.astype(int) |
| 1D index | one element | a[0], a[-1] |
| 2D index | row, then column | table[1, 2] |
| One index on a 2D array | a whole row | table[1] |
| A list of indexes | several elements at once | a[[0, 2, 4]] |
reshape | the same items in another shape | a.reshape(3, 4) |
sum / mean / min / max | simple summaries | grades.mean() |
argmax / argmin | the index of the largest / smallest | names[grades.argmax()] |
copy | a separate array | b = a.copy() |