Skip to content
Advertisement

How to make a sum in NetCDF4 by xarray

I would like to make a monthly sums of my NetCDF4 file from daily values for precipitation. However, I am quite not sure what I am doing wrong. It seems that something has changed from the code in this post: Sum a daily time series into a monthly time series with a NaN value threshold

I didn’t find anything helpful in the library documentation.

Here is my code:

import netCDF4
from netCDF4 import Dataset
import numpy as np
import xarray as xr
import pandas as pd

data = xr.open_dataset('C3S_concat_cropped.nc')
# or I can use 
data2 = Dataset("C3S_concat_cropped.nc", "r", format="NETCDF4")
print(data)
Out:
<xarray.Dataset>
Dimensions:             (lat: 115, lon: 140, time: 15157)
Coordinates:
  * lat                 (lat) float64 -7.4 -7.5 -7.6 -7.7 ... -18.6 -18.7 -18.8
  * lon                 (lon) float64 21.1 21.2 21.3 21.4 ... 34.8 34.9 35.0
  * time                (time) datetime64[ns] 1979-01-01 ... 2020-06-30
Data variables:
    Precipitation_Flux  (time, lat, lon) float32 ...

daily_dataset = xr.Dataset({'Precipitation_Flux': (['time', 'lat', 'lon'],
data['Precipitation_Flux'][:, :, :])}, coords={'lat': (data['lat'][:]), 
'lon': (data['lon'][:]), 'time': pd.date_range('1979-01-01', periods=15157)})

monthly_dataset = daily_dataset['Precipitation_Flux'].resample(indexer='M', time="1D", 
skipna=False).sum()

My ValueError:

ValueError: the first argument to .resample must be a dictionary

Advertisement

Answer

I founded that this command works for me!

monthly_dataset = daily_dataset['Precipitation_Flux'].resample(time ='M', 
skipna=False).sum()

However, the documentation of xarray.Dataset.resample can be quite confusing, as the first argument of the function – indexer is not typically written! So be aware of that! :-)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement