Calculating Seasonal Averages from Timeseries of Monthly Means

Author: Joe Hamman

The data used for this example can be found in thexarray-data repository.

Suppose we have a netCDF or xarray.Dataset of monthly mean data andwe want to calculate the seasonal average. To do this properly, we needto calculate the weighted average considering that each month has adifferent number of days.

  1. %matplotlib inline
  2. import numpy as np
  3. import pandas as pd
  4. import xarray as xr
  5. from netCDF4 import num2date
  6. import matplotlib.pyplot as plt
  7.  
  8. print("numpy version : ", np.__version__)
  9. print("pandas version : ", pd.__version__)
  10. print("xarray version : ", xr.__version__)
  1. numpy version : 1.11.1
  2. pandas version : 0.18.1
  3. xarray version : 0.8.2

Some calendar information so we can support any netCDF calendar.

  1. dpm = {'noleap': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  2. '365_day': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  3. 'standard': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  4. 'gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  5. 'proleptic_gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  6. 'all_leap': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  7. '366_day': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
  8. '360_day': [0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]}

A few calendar functions to determine the number of days in each month

If you were just using the standard calendar, it would be easy to usethe calendar.month_range function.

  1. def leap_year(year, calendar='standard'):
  2. """Determine if year is a leap year"""
  3. leap = False
  4. if ((calendar in ['standard', 'gregorian',
  5. 'proleptic_gregorian', 'julian']) and
  6. (year % 4 == 0)):
  7. leap = True
  8. if ((calendar == 'proleptic_gregorian') and
  9. (year % 100 == 0) and
  10. (year % 400 != 0)):
  11. leap = False
  12. elif ((calendar in ['standard', 'gregorian']) and
  13. (year % 100 == 0) and (year % 400 != 0) and
  14. (year < 1583)):
  15. leap = False
  16. return leap
  17.  
  18. def get_dpm(time, calendar='standard'):
  19. """
  20. return a array of days per month corresponding to the months provided in `months`
  21. """
  22. month_length = np.zeros(len(time), dtype=np.int)
  23.  
  24. cal_days = dpm[calendar]
  25.  
  26. for i, (month, year) in enumerate(zip(time.month, time.year)):
  27. month_length[i] = cal_days[month]
  28. if leap_year(year, calendar=calendar):
  29. month_length[i] += 1
  30. return month_length

Open the Dataset

  1. ds = xr.tutorial.load_dataset('rasm')
  2. print(ds)
  1. <xarray.Dataset>
  2. Dimensions: (time: 36, x: 275, y: 205)
  3. Coordinates:
  4. * time (time) datetime64[ns] 1980-09-16T12:00:00 1980-10-17 ...
  5. * y (y) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
  6. * x (x) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
  7. Data variables:
  8. Tair (time, y, x) float64 nan nan nan nan nan nan nan nan nan nan ...
  9. yc (y, x) float64 16.53 16.78 17.02 17.27 17.51 17.76 18.0 18.25 ...
  10. xc (y, x) float64 189.2 189.4 189.6 189.7 189.9 190.1 190.2 190.4 ...
  11. Attributes:
  12. title: /workspace/jhamman/processed/R1002RBRxaaa01a/lnd/temp/R1002RBRxaaa01a.vic.ha.1979-09-01.nc
  13. institution: U.W.
  14. source: RACM R1002RBRxaaa01a
  15. output_frequency: daily
  16. output_mode: averaged
  17. convention: CF-1.4
  18. references: Based on the initial model of Liang et al., 1994, JGR, 99, 14,415- 14,429.
  19. comment: Output from the Variable Infiltration Capacity (VIC) model.
  20. nco_openmp_thread_number: 1
  21. NCO: 4.3.7
  22. history: history deleted for brevity

Now for the heavy lifting:

We first have to come up with the weights, - calculate the month lengthsfor each monthly data record - calculate weights usinggroupby('time.season')

Finally, we just need to multiply our weights by the Dataset and sumalong the time dimension.

  1. # Make a DataArray with the number of days in each month, size = len(time)
  2. month_length = xr.DataArray(get_dpm(ds.time.to_index(), calendar='noleap'),
  3. coords=[ds.time], name='month_length')
  4.  
  5. # Calculate the weights by grouping by 'time.season'.
  6. # Conversion to float type ('astype(float)') only necessary for Python 2.x
  7. weights = month_length.groupby('time.season') / month_length.astype(float).groupby('time.season').sum()
  8.  
  9. # Test that the sum of the weights for each season is 1.0
  10. np.testing.assert_allclose(weights.groupby('time.season').sum().values, np.ones(4))
  11.  
  12. # Calculate the weighted average
  13. ds_weighted = (ds * weights).groupby('time.season').sum(dim='time')
  1. print(ds_weighted)
  1. <xarray.Dataset>
  2. Dimensions: (season: 4, x: 275, y: 205)
  3. Coordinates:
  4. * y (y) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
  5. * x (x) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
  6. * season (season) object 'DJF' 'JJA' 'MAM' 'SON'
  7. Data variables:
  8. Tair (season, y, x) float64 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
  9. xc (season, y, x) float64 189.2 189.4 189.6 189.7 189.9 190.1 ...
  10. yc (season, y, x) float64 16.53 16.78 17.02 17.27 17.51 17.76 18.0 ...
  1. # only used for comparisons
  2. ds_unweighted = ds.groupby('time.season').mean('time')
  3. ds_diff = ds_weighted - ds_unweighted
  1. # Quick plot to show the results
  2. notnull = pd.notnull(ds_unweighted['Tair'][0])
  3.  
  4. fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(14,12))
  5. for i, season in enumerate(('DJF', 'MAM', 'JJA', 'SON')):
  6. ds_weighted['Tair'].sel(season=season).where(notnull).plot.pcolormesh(
  7. ax=axes[i, 0], vmin=-30, vmax=30, cmap='Spectral_r',
  8. add_colorbar=True, extend='both')
  9.  
  10. ds_unweighted['Tair'].sel(season=season).where(notnull).plot.pcolormesh(
  11. ax=axes[i, 1], vmin=-30, vmax=30, cmap='Spectral_r',
  12. add_colorbar=True, extend='both')
  13.  
  14. ds_diff['Tair'].sel(season=season).where(notnull).plot.pcolormesh(
  15. ax=axes[i, 2], vmin=-0.1, vmax=.1, cmap='RdBu_r',
  16. add_colorbar=True, extend='both')
  17.  
  18. axes[i, 0].set_ylabel(season)
  19. axes[i, 1].set_ylabel('')
  20. axes[i, 2].set_ylabel('')
  21.  
  22. for ax in axes.flat:
  23. ax.axes.get_xaxis().set_ticklabels([])
  24. ax.axes.get_yaxis().set_ticklabels([])
  25. ax.axes.axis('tight')
  26. ax.set_xlabel('')
  27.  
  28. axes[0, 0].set_title('Weighted by DPM')
  29. axes[0, 1].set_title('Equal Weighting')
  30. axes[0, 2].set_title('Difference')
  31.  
  32. plt.tight_layout()
  33.  
  34. fig.suptitle('Seasonal Surface Air Temperature', fontsize=16, y=1.02)
  1. <matplotlib.text.Text at 0x117c18048>

../_images/monthly_means_output.png

  1. # Wrap it into a simple function
  2. def season_mean(ds, calendar='standard'):
  3. # Make a DataArray of season/year groups
  4. year_season = xr.DataArray(ds.time.to_index().to_period(freq='Q-NOV').to_timestamp(how='E'),
  5. coords=[ds.time], name='year_season')
  6.  
  7. # Make a DataArray with the number of days in each month, size = len(time)
  8. month_length = xr.DataArray(get_dpm(ds.time.to_index(), calendar=calendar),
  9. coords=[ds.time], name='month_length')
  10. # Calculate the weights by grouping by 'time.season'
  11. weights = month_length.groupby('time.season') / month_length.groupby('time.season').sum()
  12.  
  13. # Test that the sum of the weights for each season is 1.0
  14. np.testing.assert_allclose(weights.groupby('time.season').sum().values, np.ones(4))
  15.  
  16. # Calculate the weighted average
  17. return (ds * weights).groupby('time.season').sum(dim='time')