Calculate Time Averages from Time Series Data
Contents
Calculate Time Averages from Time Series Data#
Author: Tom Vo
Date: 05/27/22
Last Edited: 08/17/22 (v0.3.1)
Related APIs:
The data used in this example can be found through the Earth System Grid Federation (ESGF) search portal.
Overview#
Suppose we have netCDF4 files for air temperature data (tas) with monthly, daily, and 3hr frequencies.
We want to calculate averages using these files with the time dimension removed (a single time snapshot), and averages by time group (yearly, seasonal, and daily).
[2]:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import xcdat
1. Calculate averages with the time dimension removed (single snapshot)#
Related API: xarray.Dataset.temporal.average()
Helpful knowledge:
The frequency for the time interval is inferred before calculating weights.
The frequency is inferred by calculating the minimum delta between time coordinates and using the conditional logic below. This frequency is used to calculate weights.
if min_delta < pd.Timedelta(days=1): return "hour" elif min_delta >= pd.Timedelta(days=1) and min_delta < pd.Timedelta(days=28): return "day" elif min_delta >= pd.Timedelta(days=28) and min_delta < pd.Timedelta(days=365): return "month" else: return "year"
Masked (missing) data is automatically handled.
The weight of masked (missing) data are excluded when averages are calculated. This is the same as giving them a weight of 0.
Open the Dataset#
In this example, we will be calculating the time weighted averages with the time dimension removed (single snapshot) for monthly tas data.
We are using xarray’s OPeNDAP support to read a netCDF4 dataset file directly from its source. The data is not loaded over the network until we perform operations on it (e.g., temperature unit adjustment).
More information on the xarray’s OPeNDAP support can be found here.
[3]:
filepath = "http://esgf.nci.org.au/thredds/dodsC/master/CMIP6/CMIP/CSIRO/ACCESS-ESM1-5/historical/r10i1p1f1/Amon/tas/gn/v20200605/tas_Amon_ACCESS-ESM1-5_historical_r10i1p1f1_gn_185001-201412.nc"
ds = xcdat.open_dataset(filepath)
# Unit adjust (-273.15, K to C)
ds["tas"] = ds.tas - 273.15
ds
[3]:
<xarray.Dataset>
Dimensions: (time: 1980, bnds: 2, lat: 145, lon: 192)
Coordinates:
* time (time) datetime64[ns] 1850-01-16T12:00:00 ... 2014-12-16T12:00:00
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 ... 352.5 354.4 356.2 358.1
height float64 2.0
Dimensions without coordinates: bnds
Data variables:
time_bnds (time, bnds) datetime64[ns] 1850-01-01 1850-02-01 ... 2015-01-01
lat_bnds (lat, bnds) float64 -90.0 -89.38 -89.38 ... 89.38 89.38 90.0
lon_bnds (lon, bnds) float64 -0.9375 0.9375 0.9375 ... 357.2 357.2 359.1
tas (time, lat, lon) float32 -27.19 -27.19 -27.19 ... -25.29 -25.29
Attributes: (12/49)
Conventions: CF-1.7 CMIP-6.2
activity_id: CMIP
branch_method: standard
branch_time_in_child: 0.0
branch_time_in_parent: 87658.0
creation_date: 2020-06-05T04:06:11Z
... ...
version: v20200605
license: CMIP6 model data produced by CSIRO is li...
cmor_version: 3.4.0
_NCProperties: version=2,netcdf=4.6.2,hdf5=1.10.5
tracking_id: hdl:21.14100/af78ae5e-f3a6-4e99-8cfe-5f2...
DODS_EXTRA.Unlimited_Dimension: time[4]:
ds_avg = ds.temporal.average("tas", weighted=True)
[5]:
ds_avg.tas
[5]:
<xarray.DataArray 'tas' (lat: 145, lon: 192)>
array([[-48.01481628, -48.01481628, -48.01481628, ..., -48.01481628,
-48.01481628, -48.01481628],
[-44.94085363, -44.97948214, -45.01815398, ..., -44.82408252,
-44.86273067, -44.9009281 ],
[-44.11875274, -44.23060624, -44.33960158, ..., -43.76766492,
-43.88593717, -44.00303006],
...,
[-18.21076615, -18.17513373, -18.13957458, ..., -18.32720478,
-18.28428828, -18.2486193 ],
[-18.50778243, -18.49301854, -18.47902819, ..., -18.55410851,
-18.5406963 , -18.52413098],
[-19.07366375, -19.07366375, -19.07366375, ..., -19.07366375,
-19.07366375, -19.07366375]])
Coordinates:
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 2.0
Attributes:
operation: temporal_avg
mode: average
freq: month
weighted: True[6]:
ds_avg.tas.plot(label="weighted")
[6]:
<matplotlib.collections.QuadMesh at 0x7f44111d2460>
2. Calculate grouped averages#
Related API: xarray.Dataset.temporal.group_average()
Helpful knowledge:
Each specified frequency has predefined groups for grouping time coordinates.
The table below maps type of averages with its API frequency and grouping convention.
Type of Averages
API Frequency
Group By
Yearly
freq=“year”year
Monthly
freq=“month”year, month
Seasonal
freq=“season”year, season
Custom seasonal
freq="season"andseason_config={"custom_seasons": <2D ARRAY>}year, season
Daily
freq=“day”year, month, day
Hourly
freq=“hour”year, month, day, hour
The grouping conventions are based on CDAT/cdutil, except for daily and hourly means which aren’t implemented in CDAT/cdutil.
Masked (missing) data is automatically handled.
The weight of masked (missing) data are excluded when averages are calculated. This is the same as giving them a weight of 0.
Open the Dataset#
In this example, we will be calculating the weighted grouped time averages for tas data.
We are using xarray’s OPeNDAP support to read a netCDF4 dataset file directly from its source. The data is not loaded over the network until we perform operations on it (e.g., temperature unit adjustment).
More information on the xarray’s OPeNDAP support can be found here.
[7]:
filepath = "http://esgf.nci.org.au/thredds/dodsC/master/CMIP6/CMIP/CSIRO/ACCESS-ESM1-5/historical/r10i1p1f1/Amon/tas/gn/v20200605/tas_Amon_ACCESS-ESM1-5_historical_r10i1p1f1_gn_185001-201412.nc"
ds = xcdat.open_dataset(filepath)
# Unit adjust (-273.15, K to C)
ds["tas"] = ds.tas - 273.15
ds
[7]:
<xarray.Dataset>
Dimensions: (time: 1980, bnds: 2, lat: 145, lon: 192)
Coordinates:
* time (time) datetime64[ns] 1850-01-16T12:00:00 ... 2014-12-16T12:00:00
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 ... 352.5 354.4 356.2 358.1
height float64 2.0
Dimensions without coordinates: bnds
Data variables:
time_bnds (time, bnds) datetime64[ns] 1850-01-01 1850-02-01 ... 2015-01-01
lat_bnds (lat, bnds) float64 -90.0 -89.38 -89.38 ... 89.38 89.38 90.0
lon_bnds (lon, bnds) float64 -0.9375 0.9375 0.9375 ... 357.2 357.2 359.1
tas (time, lat, lon) float32 -27.19 -27.19 -27.19 ... -25.29 -25.29
Attributes: (12/49)
Conventions: CF-1.7 CMIP-6.2
activity_id: CMIP
branch_method: standard
branch_time_in_child: 0.0
branch_time_in_parent: 87658.0
creation_date: 2020-06-05T04:06:11Z
... ...
version: v20200605
license: CMIP6 model data produced by CSIRO is li...
cmor_version: 3.4.0
_NCProperties: version=2,netcdf=4.6.2,hdf5=1.10.5
tracking_id: hdl:21.14100/af78ae5e-f3a6-4e99-8cfe-5f2...
DODS_EXTRA.Unlimited_Dimension: timeYearly Averages#
Group time coordinates by year
[8]:
ds_yearly = ds.temporal.group_average("tas", freq="year", weighted=True)
[9]:
ds_yearly.tas
[9]:
<xarray.DataArray 'tas' (time: 165, lat: 145, lon: 192)>
array([[[-48.755733, -48.755733, -48.755733, ..., -48.755733,
-48.755733, -48.755733],
[-45.652065, -45.693024, -45.73506 , ..., -45.52128 ,
-45.563866, -45.60669 ],
[-44.775234, -44.905838, -45.03297 , ..., -44.37118 ,
-44.50631 , -44.640503],
...,
[-20.505976, -20.481321, -20.454565, ..., -20.588959,
-20.557522, -20.530872],
[-20.797592, -20.784252, -20.775455, ..., -20.83268 ,
-20.823357, -20.807684],
[-21.201149, -21.201149, -21.201149, ..., -21.201149,
-21.201149, -21.201149]],
[[-48.95255 , -48.95255 , -48.95255 , ..., -48.95255 ,
-48.95255 , -48.95255 ],
[-45.83191 , -45.864902, -45.89875 , ..., -45.73217 ,
-45.76544 , -45.798595],
[-44.935368, -45.037956, -45.13801 , ..., -44.61143 ,
-44.71986 , -44.829372],
...
[-14.916271, -14.899261, -14.88381 , ..., -14.99543 ,
-14.965137, -14.938532],
[-15.405922, -15.396681, -15.385955, ..., -15.432463,
-15.426056, -15.413568],
[-15.945 , -15.945 , -15.945 , ..., -15.945 ,
-15.945 , -15.945 ]],
[[-47.59732 , -47.59732 , -47.59732 , ..., -47.59732 ,
-47.59732 , -47.59732 ],
[-44.721367, -44.763428, -44.803505, ..., -44.592392,
-44.634445, -44.678226],
[-43.85032 , -43.969563, -44.08714 , ..., -43.4709 ,
-43.596764, -43.72408 ],
...,
[-14.52023 , -14.474079, -14.432307, ..., -14.675514,
-14.620932, -14.567368],
[-14.911236, -14.892309, -14.869016, ..., -14.982012,
-14.962668, -14.938723],
[-15.618406, -15.618406, -15.618406, ..., -15.618406,
-15.618406, -15.618406]]], dtype=float32)
Coordinates:
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 2.0
* time (time) object 1850-01-01 00:00:00 ... 2014-01-01 00:00:00
Attributes:
operation: temporal_avg
mode: group_average
freq: year
weighted: True
This GIF was created using xmovie.
Sample xmovie code:
import xmovie
mov = xmovie.Movie(ds_yearly_avg.tas)
mov.save("temporal-average-yearly.gif")
Seasonal Averages#
Group time coordinates by year and season
[10]:
ds_season = ds.temporal.group_average("tas", freq="season", weighted=True)
[11]:
ds_season.tas
[11]:
<xarray.DataArray 'tas' (time: 661, lat: 145, lon: 192)>
array([[[-32.705883 , -32.705883 , -32.705883 , ..., -32.705883 ,
-32.705883 , -32.705883 ],
[-30.993767 , -31.037586 , -31.089327 , ..., -30.845623 ,
-30.894127 , -30.94401 ],
[-30.02515 , -30.145437 , -30.26419 , ..., -29.660372 ,
-29.78108 , -29.902878 ],
...,
[-37.72314 , -37.685493 , -37.654167 , ..., -37.8262 ,
-37.790344 , -37.75683 ],
[-38.274647 , -38.263725 , -38.250145 , ..., -38.292183 ,
-38.290638 , -38.28456 ],
[-38.743587 , -38.743587 , -38.743587 , ..., -38.743587 ,
-38.743587 , -38.743587 ]],
[[-54.290863 , -54.290863 , -54.290863 , ..., -54.290863 ,
-54.290863 , -54.290863 ],
[-51.117714 , -51.175236 , -51.230553 , ..., -50.935165 ,
-50.99657 , -51.056145 ],
[-50.318047 , -50.486664 , -50.649567 , ..., -49.79003 ,
-49.970078 , -50.14521 ],
...
[-12.342774 , -12.2246685 , -12.106632 , ..., -12.744922 ,
-12.609088 , -12.478392 ],
[-13.126404 , -13.066109 , -13.003876 , ..., -13.306077 ,
-13.258715 , -13.19972 ],
[-14.288469 , -14.288469 , -14.288469 , ..., -14.288469 ,
-14.288469 , -14.288469 ]],
[[-28.990494 , -28.990494 , -28.990494 , ..., -28.990494 ,
-28.990494 , -28.990494 ],
[-28.192917 , -28.224579 , -28.261307 , ..., -28.095932 ,
-28.125992 , -28.15802 ],
[-27.607407 , -27.705643 , -27.805115 , ..., -27.311615 ,
-27.410828 , -27.508362 ],
...,
[-24.256271 , -24.140594 , -24.037537 , ..., -24.61853 ,
-24.488495 , -24.36644 ],
[-24.629013 , -24.613388 , -24.549866 , ..., -24.752045 ,
-24.721603 , -24.666412 ],
[-25.28923 , -25.28923 , -25.28923 , ..., -25.28923 ,
-25.28923 , -25.28923 ]]], dtype=float32)
Coordinates:
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 2.0
* time (time) object 1850-01-01 00:00:00 ... 2015-01-01 00:00:00
Attributes:
operation: temporal_avg
mode: group_average
freq: season
weighted: True
dec_mode: DJF
drop_incomplete_djf: FalseNotice that the season of each time coordinate is represented by its middle month.
“DJF” is represented by month 1 (“J”/January)
“MAM” is represented by month 4 (“A”/April)
“JJA” is represented by month 7 (“J”/July)
“SON” is represented by month 10 (“O”/October).
This is implementation design was used because datetime objects do not distinguish seasons, so the middle month is used instead.
[12]:
ds_season.time
[12]:
<xarray.DataArray 'time' (time: 661)>
array([cftime.DatetimeProlepticGregorian(1850, 1, 1, 0, 0, 0, 0, has_year_zero=True),
cftime.DatetimeProlepticGregorian(1850, 4, 1, 0, 0, 0, 0, has_year_zero=True),
cftime.DatetimeProlepticGregorian(1850, 7, 1, 0, 0, 0, 0, has_year_zero=True),
...,
cftime.DatetimeProlepticGregorian(2014, 7, 1, 0, 0, 0, 0, has_year_zero=True),
cftime.DatetimeProlepticGregorian(2014, 10, 1, 0, 0, 0, 0, has_year_zero=True),
cftime.DatetimeProlepticGregorian(2015, 1, 1, 0, 0, 0, 0, has_year_zero=True)],
dtype=object)
Coordinates:
height float64 2.0
* time (time) object 1850-01-01 00:00:00 ... 2015-01-01 00:00:00
Attributes:
bounds: time_bnds
axis: T
long_name: time
standard_name: time
_ChunkSizes: 1Monthly Averages#
Group time coordinates by year and month
For this example, we will be loading a subset of daily time series data for tas using OPeNDAP.
NOTE:
For OPeNDAP servers, the default file size request limit is 500MB in the TDS server configuration. Opening up a dataset over OPeNDAP also introduces an overhead compared to direct file access.
The workaround is to use Dask to request the data in manageable chunks, which overcomes file size limitations and can improve performance.
We have a few ways to chunk our request:
Specify
chunkswith"auto"to let Dask determine the chunksize.Specify a specify the file size to chunk on (e.g.,
"100MB") or number of chunks as an integer (100for 100 chunks).
Visit this page to learn more about chunking and performance: https://docs.xarray.dev/en/stable/user-guide/dask.html#chunking-and-performance
[13]:
# The size of this file is approximately 1.45 GB, so we will be chunking our
# request using Dask to avoid hitting the OPeNDAP file size request limit for
# this ESGF node.
ds2 = xcdat.open_dataset(
"http://esgf-data3.diasjp.net/thredds/dodsC/esg_dataroot/CMIP6/CMIP/CSIRO/ACCESS-ESM1-5/historical/r1i1p1f1/day/tas/gn/v20191115/tas_day_ACCESS-ESM1-5_historical_r1i1p1f1_gn_18500101-18991231.nc",
chunks={"time": "auto"},
)
# Unit adjust (-273.15, K to C)
ds2["tas"] = ds2.tas - 273.15
ds2
[13]:
<xarray.Dataset>
Dimensions: (time: 18262, bnds: 2, lat: 145, lon: 192)
Coordinates:
* time (time) datetime64[ns] 1850-01-01T12:00:00 ... 1899-12-31T12:00:00
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 ... 352.5 354.4 356.2 358.1
height float64 ...
Dimensions without coordinates: bnds
Data variables:
time_bnds (time, bnds) datetime64[ns] dask.array<chunksize=(18262, 2), meta=np.ndarray>
lat_bnds (lat, bnds) float64 dask.array<chunksize=(145, 2), meta=np.ndarray>
lon_bnds (lon, bnds) float64 dask.array<chunksize=(192, 2), meta=np.ndarray>
tas (time, lat, lon) float32 dask.array<chunksize=(794, 145, 192), meta=np.ndarray>
Attributes: (12/48)
Conventions: CF-1.7 CMIP-6.2
activity_id: CMIP
branch_method: standard
branch_time_in_child: 0.0
branch_time_in_parent: 21915.0
creation_date: 2019-11-15T17:30:04Z
... ...
variant_label: r1i1p1f1
version: v20191115
cmor_version: 3.4.0
tracking_id: hdl:21.14100/a9d8ba3a-bcbf-4d54-9970-cfc...
license: CMIP6 model data produced by CSIRO is li...
DODS_EXTRA.Unlimited_Dimension: time[14]:
ds2_monthly_avg = ds2.temporal.group_average("tas", freq="month", weighted=True)
[15]:
ds2_monthly_avg.tas
[15]:
<xarray.DataArray 'tas' (time: 600, lat: 145, lon: 192)>
dask.array<stack, shape=(600, 145, 192), dtype=float64, chunksize=(1, 145, 192), chunktype=numpy.ndarray>
Coordinates:
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 ...
* time (time) object 1850-01-01 00:00:00 ... 1899-12-01 00:00:00
Attributes:
operation: temporal_avg
mode: group_average
freq: month
weighted: TrueDaily Averages#
Group time coordinates by year, month, and day
For this example, we will be opening a subset of 3hr time series data for tas using OPeNDAP.
[16]:
# The size of this file is approximately 1.17 GB, so we will be chunking our
# request using Dask to avoid hitting the OPeNDAP file size request limit for
# this ESGF node.
ds3 = xcdat.open_dataset(
"http://esgf.nci.org.au/thredds/dodsC/master/CMIP6/CMIP/CSIRO/ACCESS-ESM1-5/historical/r10i1p1f1/3hr/tas/gn/v20200605/tas_3hr_ACCESS-ESM1-5_historical_r10i1p1f1_gn_201001010300-201501010000.nc",
chunks={"time": "auto"}
)
# Unit adjust (-273.15, K to C)
ds3["tas"] = ds3.tas - 273.15
[17]:
ds3.tas
[17]:
<xarray.DataArray 'tas' (time: 14608, lat: 145, lon: 192)>
dask.array<sub, shape=(14608, 145, 192), dtype=float32, chunksize=(913, 145, 192), chunktype=numpy.ndarray>
Coordinates:
* time (time) datetime64[ns] 2010-01-01T03:00:00 ... 2015-01-01
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 ...[18]:
ds3_day_avg = ds3.temporal.group_average("tas", freq="day", weighted=True)
[19]:
ds3_day_avg.tas
[19]:
<xarray.DataArray 'tas' (time: 1827, lat: 145, lon: 192)>
dask.array<stack, shape=(1827, 145, 192), dtype=float64, chunksize=(1, 145, 192), chunktype=numpy.ndarray>
Coordinates:
* lat (lat) float64 -90.0 -88.75 -87.5 -86.25 ... 86.25 87.5 88.75 90.0
* lon (lon) float64 0.0 1.875 3.75 5.625 7.5 ... 352.5 354.4 356.2 358.1
height float64 ...
* time (time) object 2010-01-01 00:00:00 ... 2015-01-01 00:00:00
Attributes:
operation: temporal_avg
mode: group_average
freq: day
weighted: True