Data Science with Python

NumPy Arrays

Python Basics · Lesson 5 of 30

NumPy is an open source Python library for working with numerical data. Its main object is the array: a grid of values that all have the same type. The first run of this lesson downloads NumPy, so it takes a few seconds.

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6])
print(a)
print(a.shape, a.dtype)

Maths on whole arrays

Arithmetic applies to every element at once. You do not write a loop.

import numpy as np

prices = np.array([900, 20, 250])
units = np.array([3, 10, 4])

revenue = prices * units
print(revenue)
print(revenue.sum(), revenue.mean(), revenue.max())

Two dimensions

An array can have more than one dimension. shape reports the size of each one, and reshape changes the layout without changing the data.

import numpy as np

m = np.arange(12).reshape(3, 4)
print(m)
print(m.shape)
print(m[0])           # first row
print(m[:, 1])        # second column
print(m.sum(axis=0))  # sum of each column

Selecting with a condition

A comparison produces an array of True and False values. Use it inside square brackets to keep only the matching elements.

import numpy as np

scores = np.array([72, 88, 95, 61, 79])
print(scores >= 75)
print(scores[scores >= 75])

Try it

Create temps_c = np.array([18.5, 22.0, 30.1, 15.2]) and convert it to Fahrenheit with temps_c * 9 / 5 + 32. Then print only the values above 70.