Skip to content
Advertisement

Calculating monthly mean from daily netcdf file in python

Hello I have a netcdf file with daily data. Shape of the file is (5844, 89, 89) i.e 16 years data. I tried to get monthly average from daily data. I am looking for simillar to resample function in pandas dataframe. Is there anyways to do that in python. As I know it is very easy to calculate by using cdo and nco but I am looking in python.

Sample code that I used to read netcdf file is:

import netCDF4
from netCDF4 import Dataset
fh = Dataset(ncfile, mode='r')
time = fh.variables['time'][:]
lon = fh.variables['longitude'][:]
lat = fh.variables['latitude'][:]
data = fh.variables['t2m'][:]
data.shape

Advertisement

Answer

@ jhamman Thank you for suggesting xarray.resample. It is simpler than I thought and the answer to my question is:

import xarray as xr
ds = xr.open_dataset(nc_file)
monthly_data = ds.resample(freq = 'm', dim = 'time', how = 'mean')
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement