Introduction to NumPy

In [1]:
import numpy as np

Load in the data for the exercise:

In [2]:
with np.load("weather_data.npz") as weather:
    data = weather["rain_history"]

Plot the data to see what range of values we're dealing with:

In [3]:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(data)
Out[3]:
[<matplotlib.lines.Line2D at 0x7f521591c8b0>]

The mean should be around 50 or 60:

In [4]:
np.mean(data)
Out[4]:
54.787499999999994

And the standard deviation looks to be about 10:

In [5]:
np.std(data)
Out[5]:
9.355232731700784

We can write a function which calculates based on an array:

In [6]:
def variation(x):
    return np.std(x) / np.mean(x)

And call it like any other function:

In [7]:
variation(data)
Out[7]:
0.17075487532193995

Because we're using the NumPy functions, it also works on Python lists of numbers:

In [8]:
variation([50, 60, 51, 49, 53])
Out[8]:
0.07470297606231369

As well as single values:

In [9]:
variation(7)
Out[9]:
0.0