Lesson

NumPy Arrays: Calculating on a Whole Column of Numbers

Convert the fuel use and weight of 398 real car models with NumPy arrays instead of loops: arithmetic on a whole array, shape and type, indexing and slicing of a table, a boolean mask, a statistic per column or per row, missing values, and a slice that is a view.

Last updated:


In this lesson we learn to calculate on whole columns of numbers with NumPy arrays:
arithmetic without a loop, shape and type, indexing, a boolean mask, axis, missing values and views.

Fuel use in liters per 100 kilometers

A technical content team prepares a sheet of car models of 1970 to 1982 for European readers, with fuel use in liters per 100 km and weight in kilograms; the data give fuel economy in miles per gallon (mpg) and weight in pounds.
A pound is exactly 0.45359237 kg. A mile is 1.609344 km and a US gallon is 3.785411784 liters, so a car that drives $m$ miles on a gallon uses 3.785411784 liters for $1.609344,m$ km, and for 100 km:

3.7854117841.609344 m⋅100=235.21458…m≈235.215m\frac{3.785411784}{1.609344\,m}\cdot 100 = \frac{235.21458\ldots}{m} \approx \frac{235.215}{m}

auto-mpg.csv holds 398 real car models (Auto MPG, UCI Machine Learning Repository, CC BY 4.0; description):
796 calculations for the sheet. csv reads two columns into lists, as in rows from a file:

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
If you press Stop or reload, run the page again from the top.
The first run of the page loads the library, so it can take a moment.

import csv

with open(
    'auto-mpg.csv', newline='', encoding='utf-8'
) as file:
    rows = list(csv.DictReader(file))
mpg_list = [float(row['mpg']) for row in rows]
weight_list = [float(row['weight']) for row in rows]
print(len(mpg_list), mpg_list[:5])
398 [18.0, 15.0, 18.0, 16.0, 17.0]

Predict: what happens when we divide 235.215 by the whole list, 235.215 / mpg_list?

Show the answer
235.215 / mpg_list
TypeError: unsupported operand type(s) for /: 'float' and 'list'

A list is a collection of any values, not a collection of numbers, so Python does not define division of a number by a list.
Multiplication does not fail, and that is a trap: mpg_list * 2 is the list repeated twice, 796 values.

With lists, the conversion is a loop, [235.215 / m for m in mpg_list], and so is every other calculation:
one more loop for each column and for each statistic of a column.

Arithmetic on a whole array

NumPy is a Python library for calculating on many numbers at once; after import numpy as np its functions are written np. and a name.
np.array(list) makes an array: values of one type side by side, and an arithmetic operation on it acts on every value.
np.round(array, digits) rounds every value of an array, as round(x, digits) rounds one number.

Predict what 235.215 / mpg returns once mpg is an array.

import numpy as np
mpg = np.array(mpg_list)
weight = np.array(weight_list)
liters = 235.215 / mpg
kg = weight * 0.45359237
print(type(mpg))
print(np.round(liters[:5], 1))
print(np.round(kg[:5]))
<class 'numpy.ndarray'>
[13.1 15.7 13.1 14.7 13.8]
[1589. 1675. 1559. 1557. 1564.]

This is the sheet of the opening, without a loop: the first car, the 1970 Chevrolet Chevelle Malibu, uses 13.1 liters per 100 km and weighs 1,589 kg.
numpy.ndarray is the type of an array.

A speed test

A loop runs a line of Python per number; an array expression runs one loop inside NumPy, in compiled code (translated in advance into processor instructions).
The box times both on 1 to 1,000,000 (_ separates thousands), a test and not data; time.perf_counter() returns a time in seconds.

import time

big_list = list(range(1, 1_000_001))
big = np.array(big_list)
start = time.perf_counter()
result_list = [235.215 / m for m in big_list]
loop_seconds = time.perf_counter() - start
start = time.perf_counter()
result = 235.215 / big
array_seconds = time.perf_counter() - start
print('loop: ', round(loop_seconds, 4), 'seconds')
print('array:', round(array_seconds, 4), 'seconds')
loop:  0.0612 seconds
array: 0.0065 seconds

This output is from one run in the browser; times change between computers and runs.
In our runs in the browser the array was 9 to 14 times faster.

Practice

The size of an engine (displacement) is in the file in cubic inches; one cubic inch is exactly 0.016387064 liters.

Your turn. Make an array of the displacement of all the cars from the list rows (the column displacement), convert it to liters, and print the first five values rounded to two digits after the decimal point.

# your code here
Show a hint

Build the list as mpg_list was built, from the column displacement; after np.array, one multiplication converts the whole array.

Show a solution
displacement = np.array(
    [float(row['displacement']) for row in rows]
)
displacement_liters = displacement * 0.016387064
print(np.round(displacement_liters[:5], 2))
[5.03 5.74 5.21 4.98 4.95]
Show a common mistake and why it happens
displacement = np.array(
    [float(row['displacement']) for row in rows]
)
displacement_liters = displacement / 0.016387064
print(np.round(displacement_liters[:5], 2))

Dividing by the size of a cubic inch in liters gives tens of thousands, such as 18734.29 for an engine of 307 cubic inches.
A liter is larger than a cubic inch, so the number of liters must be smaller than the number of cubic inches:
a conversion to a larger unit multiplies by the size of the old unit in the new one.

Shape and type of a table

Every array knows its shape, the number of values along each direction, in the attribute shape; the number of directions, the dimensions, in ndim; and the type of its values, its dtype (data type), in dtype.
The type float64 is a number with a decimal point stored in 64 bits.

np.genfromtxt reads a text file of numbers into an array: delimiter=',' says that commas separate the values, skip_header=1 skips the line of column names, and usecols chooses the columns by index, here the seven numeric ones (without the text columns origin and name).

cars = np.genfromtxt(
    'auto-mpg.csv', delimiter=',', skip_header=1,
    usecols=(0, 1, 2, 3, 4, 5, 6),
)
print(mpg.shape, mpg.ndim)
print(cars.shape, cars.ndim, cars.dtype)
(398,) 1
(398, 7) 2 float64

mpg has one direction of 398 values; cars has 398 rows, one per car, and 7 columns, one per measurement.
All its values are float64, even the cylinders, because an array holds one type.

Changing the type with astype

The method astype(type) returns a copy of the array with another type of values; astype(int) makes whole numbers.
It cuts off the fraction and does not round: 13.07 and 13.84 both become 13.

print(np.round(liters[:5], 2))
print(liters[:5].astype(int))
print(np.round(liters[:5]).astype(int))
[13.07 15.68 13.07 14.7  13.84]
[13 15 13 14 13]
[13 16 13 15 14]

To get the nearest whole number, round first and change the type after.

Check. What does print(a, a.shape) show for a = np.array([2.9, 7.5]).astype(int)?

Show the answer
a = np.array([2.9, 7.5]).astype(int)
print(a, a.shape)
[2 7] (2,)

The fractions are cut off, not rounded, and the shape is one direction of two values.

One value, one column, a block

A value of a table is reached with two indexes in one pair of square brackets, cars[row, column], counted from 0.
The columns of cars are in the order of the file: 0 miles per gallon, 1 cylinders, 2 displacement (cubic inches), 3 horsepower, 4 weight (pounds), 5 acceleration (seconds from 0 to 60 miles per hour), 6 model year (70 means 1970).

A colon alone means every index along that direction, and start:end is a slice, from start up to end without end itself, as for a slice of a list.

print(cars[0, 4])
print(cars[:3, 0])
print(cars[:3, 0:2])
3504.0
[18. 15. 18.]
[[18.  8.]
 [15.  8.]
 [18.  8.]]

cars[0, 4] is the weight of the first car, cars[:3, 0] a column of three values, and cars[:3, 0:2] a block of shape (3, 2), without column 2.
A negative index counts from the end: cars[-1] is the last row.

Check. What is the shape of cars[-3:, 5:7], and which measurements does it hold?

Show the answer
print(cars[-3:, 5:7])
[[11.6 82. ]
 [18.6 82. ]
 [19.4 82. ]]

The shape is (3, 2): the last three cars, with columns 5 and 6, the acceleration and the model year; column 7 does not exist and is not included.

Selecting rows with a boolean mask

The specification sheet now needs the economical models, under 8 liters per 100 km.
A comparison of an array with a number compares every value.

Predict what liters < 8 returns, and its shape.

efficient = liters < 8
print(efficient[:5], efficient.shape)
print(efficient.sum())
[False False False False False] (398,)
97

The result is a boolean mask: an array of True and False with the shape of liters, one answer per car.
In a sum True counts as 1 and False as 0, so efficient.sum() counts the economical models:
97 of 398.

A mask inside square brackets keeps the rows where it is True; liters follows the order of the rows of cars, so its mask fits them.
len of an array returns its number of rows.

economical = cars[efficient]
print(economical.shape, len(economical))
(97, 7) 97

Two conditions: & and |

Two masks are combined value by value: & keeps a row where both are True (and), and | where at least one is True (or).
Each comparison must be in parentheses, because Python computes & before < and ==.
Without parentheses, liters < 8 & cylinders == 4 first tries 8 & cylinders and stops with an error.

cylinders = cars[:, 1]
print(((liters < 8) & (cylinders == 4)).sum())
print(((liters < 8) | (cylinders == 4)).sum())
93
208

Of the 97 economical models, 93 have four cylinders; 208 models are economical or have four cylinders.

Practice

Your turn. How many car models of model year 1980 or later use less than 8 liters per 100 km?
Print the count as one number.

# your code here
Show a hint

The model year is column 6, and 1980 is written as 80.

Show a solution
year = cars[:, 6]
print(((liters < 8) & (year >= 80)).sum())
59
Show a common mistake and why it happens
year = cars[:, 6]
print(((liters < 8) | (year >= 80)).sum())

The operator | keeps a model that meets at least one condition, so it also counts economical models from before 1980 and the uneconomical ones from 1980 on:
127 instead of 59.

A statistic per column or per row: axis

A statistic of a whole table mixes columns that measure different things.
The argument axis says along which direction to compute: axis=0 goes down the rows and returns one result per column; axis=1 goes across the columns and returns one result per row, which has a meaning when the columns share a unit.

iowa-electricity.csv (description; U.S. Energy Information Administration, public domain) holds the net generation of electricity in the US state of Iowa in thousand megawatt-hours (MWh), by source, 2001 to 2017 (a year is written as its first day):
a long table of 51 rows of year, source and value. We check its order:

with open(
    'iowa-electricity.csv', newline='', encoding='utf-8'
) as file:
    power_rows = list(csv.DictReader(file))
print(len(power_rows))
print([power_rows[i]['source'] for i in (0, 17, 34)])
print(power_rows[0]['year'], power_rows[16]['year'])
51
['Fossil Fuels', 'Nuclear Energy', 'Renewables']
2001-01-01 2017-01-01

A table of years and sources

The rows are ordered by source and then by year, 17 years per source with none missing.
reshape(3, 17) fills 3 rows of 17 values one after the other, so each row is one source; this works only because of that order.
The attribute T (transpose) swaps rows and columns: power has a row per year and a column per source.

generation = np.array(
    [float(row['net_generation']) for row in power_rows]
)
power = generation.reshape(3, 17).T
print(power.shape, power[0], power[-1])
total = power.sum(axis=1)
print(total[0], total[-1])
print(np.round(power.mean(axis=0)))
(17, 3) [35361.  3853.  1437.] [29329.  5214. 21933.]
40651.0 56476.0
[36478.  4712.  9660.]

Iowa generated 40,651 thousand MWh in 2001 and 56,476 in 2017 (axis=1, a sum per year).
A year averaged 36,478 thousand MWh from fossil fuels, 4,712 from nuclear energy and 9,660 from renewables (axis=0, a mean per source).

Practice

Your turn. Print the largest yearly generation of each of the three sources over the 17 years, in thousand MWh.

# your code here
Show a hint

One result for each column: which value of axis is that?

Show a solution
print(power.max(axis=0))
[42750.  5321. 21933.]
Show a common mistake and why it happens
print(power.max(axis=1))

axis=1 takes the largest of the three sources in each year, so the result is 17 values, one per year, and not one value per source.

Missing values

The horsepower of 6 models is missing, and np.genfromtxt writes each empty field as nan (not a number), the float64 value for a missing number (np.nan in code; pandas calls it NaN).
Every calculation with nan returns nan.

Predict what np.nan == np.nan returns.

horsepower = cars[:, 3]
print(np.nan + 1, horsepower.mean())
print(np.nan == np.nan)
nan nan
False

One nan in a sum makes the sum nan. nan is not equal even to itself, so == cannot find it.

Finding and skipping nan

The function np.isnan(array) returns a mask that is True where a value is nan; np.nanmean and np.nanmax compute the mean and the largest value of the other values.

missing = np.isnan(horsepower)
print(missing.sum(), len(horsepower))
print(round(np.nanmean(horsepower), 1), np.nanmax(horsepower))
6 398
104.5 230.0

Of the 398 models, 392 have a measured horsepower: “how many models” and “how many models were measured” are two different counts.

Two arrays of the same shape are combined value by value: kg / horsepower is the weight per horsepower of each car (kg follows the rows of the file).

Check. How many values of kg / horsepower are nan, and what is their mean, skipping nan, rounded to one digit?

Show the answer
kg_per_hp = kg / horsepower
print(np.isnan(kg_per_hp).sum(), round(np.nanmean(kg_per_hp), 1))
6 13.4

A division by nan gives nan, so the six cars without horsepower have no value; the others carry 13.4 kg per horsepower on average.

Removing rows with nan

The operator ~ flips a mask: ~missing is True where the horsepower was measured.
With it we keep the complete rows only; np.nanmean also takes axis.

complete = cars[~missing]
print(complete.shape)
print(np.round(complete.mean(axis=0), 1))
print(np.round(np.nanmean(cars, axis=0), 1))
(392, 7)
[  23.4    5.5  194.4  104.5 2977.6   15.5   76. ]
[  23.5    5.5  193.4  104.5 2970.4   15.6   76. ]

The mean horsepower is the same, 104.5, but the other columns changed:
removing a row removes all the measurements of that car, while np.nanmean skips a missing value in its own column only.
To compare two columns car by car, we keep the complete rows.

Practice

Your turn. What is the mean horsepower of the four-cylinder models, over the models whose horsepower was measured?
Print it rounded to one digit after the decimal point.

# your code here
Show a hint

Check whether the selected models have a missing value.

Show a solution
four = cars[:, 1] == 4
print(round(np.nanmean(cars[four, 3]), 1))
78.3

Five of the six models with a missing horsepower have four cylinders.

Show a common mistake and why it happens
four = cars[:, 1] == 4
print(round(np.mean(cars[four, 3]), 1))

np.mean does not ignore nan, and the selected models include five with a missing horsepower, so the result is nan.

A slice is a view

A slice of a list is a new list; a slice of an array is a view:
the same values in memory, not a copy. The box works on demo, made with the method copy(), which makes an array with its own values.

Predict what the last line prints.

demo = liters.copy()
top = demo[:3]
top[0] = 0
print(np.round(demo[:3], 1))
[ 0.  15.7 13.1]

The first value of demo is now 0, although we changed only top:
a change through a view changes the original. A selection with a mask, array[mask], is different:
it returns a copy.

Check. After sel = demo[demo < 8] and sel[0] = 100, does demo change?

Show the answer
sel = demo[demo < 8]
sel[0] = 100
print((demo == 100).sum())
0

No value of demo became 100: a mask returns a copy, so sel has values of its own.

Keep in mind

  • np.array(list) makes an array: values of one type side by side, and an operation acts on every value: 235.215 / mpg, weight * 0.45359237.
  • A calculation on a whole array replaces a loop: one line of code, and on a million numbers 9 to 14 times faster in our runs in the browser.
  • shape, ndim and dtype give the shape, the number of dimensions and the type of the values; astype(int) cuts off the fraction and does not round.
  • cars[row, column]: a colon alone is the whole direction, and the end of a slice is not included.
  • A comparison returns a boolean mask; array[mask] keeps the rows where it is True, and mask.sum() counts them. Combine with & and |, each comparison in parentheses.
  • axis=0 gives one result per column, and axis=1 one result per row; reshape and T turn a long column into such a table, when its order allows it.
  • A missing number is nan: any calculation with it is nan. np.isnan finds it, np.nanmean and np.nanmax ignore it, and array[~mask] removes whole rows.
  • A slice of an array is a view of the original, and a mask returns a copy; copy() makes an independent copy.