see : https://github.com/pydata/xarray/blob/master/examples/xray_seasonal_means.ipynb

Calculating Seasonal Averages from Timeseries of Monthly Means

Author: Joe Hamman

The data used for this example can be found in the xray-data repository. You may need to change the path to RASM_example_data.nc below.

Suppose we have a netCDF or xray Dataset of monthly mean data and we want to calculate the seasonal average. To do this properly, we need to calculate the weighted average considering that each month has a different number of days.


In [4]:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

In [5]:
import xarray

In [7]:
from netCDF4 import num2date

In [8]:
from netCDF4 import Dataset

In [16]:
# !conda list

In [13]:
print("numpy version  :", np.__version__)
print("pandas version :", pd.__version__)
print("xray version   :", xarray.__version__)


numpy version  : 1.11.0
pandas version : 0.18.1
xray version   : 0.7.2

Some calendar information so we can support any netCDF calendar.


In [17]:
dpm = {'noleap': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '365_day': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'standard': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'proleptic_gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'all_leap': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '366_day': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '360_day': [0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]} 
dpm


Out[17]:
{'360_day': [0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
 '365_day': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 '366_day': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 'all_leap': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 'gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 'noleap': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 'proleptic_gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
 'standard': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]}

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 use the calendar.month_range function.


In [19]:
def leap_year(year, calendar='standard'):
    """Determine if year is a leap year"""
    leap = False
    if ((calendar in ['standard', 'gregorian',
        'proleptic_gregorian', 'julian']) and
        (year % 4 == 0)):
        leap = True
        if ((calendar == 'proleptic_gregorian') and
            (year % 100 == 0) and
            (year % 400 != 0)):
            leap = False
        elif ((calendar in ['standard', 'gregorian']) and
                 (year % 100 == 0) and (year % 400 != 0) and
                 (year < 1583)):
            leap = False
    return leap

In [22]:
leap_year(2016), leap_year(2004), leap_year(2001), leap_year(2000)


Out[22]:
(True, True, False, True)

In [23]:
leap_year(2100), leap_year(2200), leap_year(2300),leap_year(2400),


Out[23]:
(True, True, True, True)

In [26]:
leap_year(2100, "proleptic_gregorian"), \
leap_year(2200, "proleptic_gregorian"), \
leap_year(2300, "proleptic_gregorian"), \
leap_year(2400, "proleptic_gregorian")


Out[26]:
(False, False, False, True)

In [27]:
def get_dpm(time, calendar='standard'):
    """
    return a array of days per month corresponding to the months provided in `months`
    """
    month_length = np.zeros(len(time), dtype=np.int)
    
    cal_days = dpm[calendar]
    
    for i, (month, year) in enumerate(zip(time.month, time.year)):
        month_length[i] = cal_days[month]
        if leap_year(year, calendar=calendar):
            month_length[i] += 1
    return month_length

In [30]:
import datetime

In [49]:
# get_dpm(datetime.datetime(2016, 5, 8))

In [44]:
datetime.datetime(2002, 12, 25)


Out[44]:
datetime.datetime(2002, 12, 25, 0, 0)

In [ ]: