Skip to main content

np_seasonal_rainfall.py


"""
Numpy exercise: Spring rainfall
Consider the following array, which contains the monthly UK rainfall of 2012 in mm, starting at January.
Rainfall_2012=np.array([110.9, 60.0, 37.0, 128.0, 65.8, 149.0, 118.9, 111.3, 112.9, 126.2, 135.5, 179.4])
Rainfall[0] is the rainfall for January
Rainfall[1] is the rainfall for Febraury
Rainfall[-1] is the rainfall for December
December 2011 rainfall was 168.1mm
Calculate the total rainfall by season with:
Winter : Dec 11 , Jan 12, Feb 12
Sprint : Mar-May 12
Summer : Jun-Aug 12
Autumn : Sep-Nov 12
Rather than specifying which element of the array to add, try re-arranging the shape of the array and summing over an axis.
Solution written by Lauren J Gregoire
"""
import numpy as np
rainfall_2012=np.array([110.9,  60.0,  37.0, 128.0,  65.8, 149.0,
                     118.9, 111.3, 112.9, 126.2, 135.5, 179.4])
concat_rainfall=np.concatenate((np.array([168.1]), rainfall_2012[0:11]))
print concat_rainfall
rainfall_2D=concat_rainfall.reshape(4,3)
print rainfall_2D
rainfall_seas=rainfall_2D.sum(axis=1)
print rainfall_seas
# to double check the operations
# calculate independently the spring rainfall
rainfall_spring=rainfall_2012[2:5].sum()
print rainfall_spring