Asiman Data School

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

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. 1.What NumPy is, how to import it, and how an array differs from a list
  2. 2.Creating arrays from lists, and with zeros, ones, full, arange, linspace
  3. 3.The properties ndim, shape, size and dtype
  4. 4.Data types of arrays, and converting with astype
  5. 5.Indexing a 1D array and a 2D array, and changing elements
  6. 6.Taking several elements at once with a list of indexes
  7. 7.Changing the shape with reshape
  8. 8.Going through an array with loops, simple summaries, and copying an array
  9. 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:

Python
import numpy as np

print(np.__version__)

Output

2.4.6

1.3The first array

np.array(...) turns a list into an array:

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

Why not just a list?
ListNumPy array
Types of the itemsany mixone type for all items
Made forgeneral collectionsnumbers and calculation
Dimensionsa list of lists for a tablereal rows and columns
Sizecan grow (append)fixed when created
Speed with many numbersslowfast

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

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

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

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

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

Python
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

Python
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

Create an array from the list [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
Python
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:

The properties of an array
PropertyMeaningExample for a table with 2 rows and 3 columns
ndimthe number of dimensions2
shapethe size in each dimension, as a tuple(2, 3)
sizethe total number of items6
dtypethe data type of the itemsint64

They are attributes, so they are written without parentheses.

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

Python
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

10203040

4 items

ndim
1
shape
(4,)
size
4

Two dimensions

3 columns

2 rows

123
456
ndim
2
shape
(2, 3)
size
6
The shape has one number for each dimension. For a table the rows come first, then the columns, and the size is 2 × 3 = 6 items.

2.1len gives the number of rows

Python
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

Create an array with the numbers 5, 10, 15, 20, 25 and print its shape, size and dtype, each on its own line.
Show a hint
They are attributes: a.shape, a.size, a.dtype, without parentheses. On this page the last line shows int32, and that counts as right.
Show the solution
Python
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

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

Python
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

Python
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

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

linspace: a fixed number of evenly spaced values
arange(start, stop, step)linspace(start, stop, count)
You choosethe stephow many values
Stop valuenot includedincluded

Move the sliders and watch where the values land.

np.arange(0, 20, 5)
051015

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

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

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

Change it and run: run it several times. The numbers are different each time.

Random numbers
FunctionWhat it makesExample
np.array(list)an array from a listnp.array([1, 2, 3])
np.zeros(shape)all zerosnp.zeros((2, 3))
np.ones(shape)all onesnp.ones(4)
np.full(shape, value)one value everywherenp.full(5, 7)
np.arange(start, stop, step)numbers with a stepnp.arange(0, 20, 5)
np.linspace(start, stop, count)a number of evenly spaced valuesnp.linspace(0, 1, 5)
np.eye(n)the identity matrixnp.eye(3)
np.random.randint(low, high, count)random whole numbersnp.random.randint(1, 7, 5)

Try it yourself

Create 5 evenly spaced values from 0 to 10 with 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
Python
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.

Data types
dtypeMeaningExample
int64whole numbersnp.array([1, 2, 3])
float64decimalsnp.array([1.5, 2.0])
boolTrue and Falsenp.array([True, False])
<U...textnp.array(["a", "b"])
Python
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=

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

Python
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

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

Python
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

Create the array [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
Python
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.

index01234
value1020304050
negative-5-4-3-2-1
Counting from the front starts at 0. Counting from the back starts at -1, so a[-1] is always the last element.
Python
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:

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

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

Python
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 0column 1column 2
row 0123
row 1456
row 2789
table[1, 2]: go down to row 1, then across to column 2. The element where they cross is 6.
Python
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 0column 1column 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

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

Python
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

Python
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

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

An index out of range
You writeYou 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] = 0changes one element
table[1] = [0, 0, 0]changes a whole row

Try it yourself

From 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
The 6 is in row 1, column 2: table[1, 2]. The last row is table[-1]. Changing one element: table[0, 1] = 0.
Show the solution
Python
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:

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

The elements of the array a with their indexes; press one to add its index
01234
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:

Python
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

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

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

rows02
columns20
pair(0, 2)(2, 0)
element37
column 0column 1column 2
row 0123
row 1456
row 2789
Read the two lists from top to bottom: the first row index goes with the first column index, the second with the second. Two pairs, so the result has two elements: [3 7].

6.3Changing several elements

Python
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

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

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

Python
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

Python
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

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

rows
columns
a = np.arange(1, 13)
print(a.reshape(3, 4))
1234
5678
9101112

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

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

Python
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

Create the numbers 10, 20, 30, up to 80 with 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
Python
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

Python
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

Python
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

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

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

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

indexgradesnames
085Aylin
192Murad
278Leyla
360Kamran
495Nigar
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:

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

Python
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

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

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

Python
import numpy as np

a = np.array([1, 2, 3])
print(a.shape())

Error

TypeError: 'tuple' object is not callable

Rows of different lengths:

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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

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

Python
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. 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 is a[0] and the last one is a[-1]. One print with a comma puts both on one line.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.arange(10)
    print(a[0], a[-1])

    Output

    0 9
  2. 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. Then a[2] = 7.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.zeros(6, dtype=int)
    a[2] = 7
    print(a)

    Output

    [0 0 7 0 0 0]
  3. 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 16 gives [ 4 8 15 16] 167 gives [7] 7-3 -9 -1 gives [-3 -9 -1] -1
    Show a hint
    np.array(numbers) turns the list into an array. The largest element is a.max(). Print both with one print(a, a.max()).
    Show one possible solution
    Python
    import numpy as np
    
    numbers = list(map(int, input().split()))
    a = np.array(numbers)
    print(a, a.max())

    Output

    [ 4  8 15 16] 16
  4. 4.Create the array [[1, 2], [3, 4], [5, 6]] and print its shape, its number of rows and the element in row 2, column 1, each on its own line.
    Show a hint
    len(table) or table.shape[0] is the number of rows. Row 2, column 1 is table[2, 1]: counting starts at 0.
    Show one possible solution
    Python
    import 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.

  1. 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
    Python
    import 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
  2. 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 50 gives 3010 20 30 40 gives 307 gives 7
    Show a hint
    The middle index is a.size // 2. For 5 elements that is index 2, for 4 elements it is also index 2.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    print(a[a.size // 2])

    Output

    30
  3. 7.Given names = np.array(["Aylin", "Murad", "Leyla", "Kamran"]) and grades = 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 in names.
    Show one possible solution
    Python
    import numpy as np
    
    names = np.array(["Aylin", "Murad", "Leyla", "Kamran"])
    grades = np.array([85, 92, 78, 45])
    print(names[grades.argmin()])

    Output

    Kamran
  4. 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 4 gives [10 30 50]10 20 30 40 50, 4 0 gives [50 10]
    Show a hint
    A list of indexes goes inside the brackets: a[indexes]. Here indexes already is a list, so no extra brackets are needed.
    Show one possible solution
    Python
    import numpy as np
    
    a = np.array(list(map(int, input().split())))
    indexes = list(map(int, input().split()))
    print(a[indexes])

    Output

    [10 30 50]
  5. 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 like table[0, 0] = 1 work, and so does one line with two lists: table[[0, 1, 2], [0, 1, 2]] = 1.
    Show one possible solution
    Python
    import 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.

  1. 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, start total = 0 and add table[i, j] for every row i. Print with print("Column", j, "sum:", total).
    Show one possible solution
    Python
    import 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
  2. 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 5 gives 210 10 10 gives 05 gives 0
    Show a hint
    Store a.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
    Python
    import 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
  3. 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
    Python
    import 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]
  4. 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 6 gives [4 5 6] [1 2 3]7 7 7 0 0 0 gives [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
    Python
    import 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]
  5. 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 10 gives 1 03 3, 1 2 3 4 5 6 7 8 9 gives 2 2
    Show a hint
    Keep the best position in two variables that start at 0, 0. Go through every i and j with two loops, and when table[i, j] is larger than the element at the best position, store i and j. Return both: return best_row, best_column.
    Show one possible solution
    Python
    import 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
  6. 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 with best = 0 and compare grades[i, j] with grades[best, j] for every student i. Print with print("Exam", j, "best student:", best).
    Show one possible solution
    Python
    import 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.

Question 1

1.What is the type of the items of this array?

a = np.array([1, 2, 3.5])

Question 2

2.What does this print?

table = np.array([[1, 2, 3], [4, 5, 6]])
print(table.shape, table.size, len(table))

Question 3

3.What does this print?

print(np.arange(0, 6, 2))

Question 4

4.How many values does np.linspace(0, 1, 5) give, and is 1 one of them?

Question 5

5.What does this print?

a = np.array([1, 2, 3])
a[0] = 9.9
print(a)

Question 6

6.What does this print?

table = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(table[1, 2], table[2, 1])

Question 7

7.table is a 2D array with 3 rows and 4 columns. What does table[-1] give?

Question 8

8.What does this print?

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

Question 9

9.What does this print?

table = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(table[[0, 2], [1, 0]])

Question 10

10.a = np.arange(12). Which line gives an error?

Question 11

11.What does this print?

grades = np.array([70, 95, 60, 88])
print(grades.argmax(), grades.max())

Question 12

12.What does this print?

a = np.array([1, 2, 3])
b = a
c = a.copy()
b[0] = 5
c[1] = 7
print(a)

0 of 12 answered.

13Quick summary

Quick summary
ConceptWhat it doesExample
import numpy as nploads NumPynp.array([1, 2, 3])
Arraya grid of values of one typenp.array([[1, 2], [3, 4]])
ndim / shape / sizedimensions / size per dimension / number of itemstable.shape gives (2, 3)
dtypethe type of the itemsint64, float64
zeros / ones / fullarrays filled with one valuenp.zeros((2, 3))
arangenumbers with a stepnp.arange(0, 20, 5)
linspacea number of evenly spaced valuesnp.linspace(0, 1, 5)
astypea new array with another typeprices.astype(int)
1D indexone elementa[0], a[-1]
2D indexrow, then columntable[1, 2]
One index on a 2D arraya whole rowtable[1]
A list of indexesseveral elements at oncea[[0, 2, 4]]
reshapethe same items in another shapea.reshape(3, 4)
sum / mean / min / maxsimple summariesgrades.mean()
argmax / argminthe index of the largest / smallestnames[grades.argmax()]
copya separate arrayb = a.copy()