Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split single monthly NetCDF file into daily averaged NetCDF multiple files using xarray

I have 1 NetCDF file for the month of September 2007. It contains 6 hourly data for certain lat/long with wind and humidity variables. Each variable is in a shape of (120, 45, 93): 120 times (4 times a day), 45 latitudes and 93 longitudes. With the following code, I am able to get daily average data for all variables. Now, each variable is of shape (30, 45, 93). Time is an integer and has a unit of 'hours since 1900-01-01 00:00:00.0'.

From this daily averaged data, how can I split into 30 different NetCDF files for each day, with the file name containing YYYY:MM:DD time format?

import xarray as xr
monthly_data = xr.open_dataset('interim_2007-09-01to2007-09-31.nc') 
daily_data = monthly_data.resample(time='1D').mean()
like image 994
Pramod Avatar asked Feb 11 '26 06:02

Pramod


1 Answers

Xarray has a top level function for times like this - xarray.save_mfdataset. In your case, you would want to use groupby to break your dataset into logical chunks and then create a list of corresponding file names. From there, just let save_mfdataset do the rest.

dates, datasets = zip(*ds.resample(time='1D').mean('time').groupby('time'))
filenames = [pd.to_datetime(date).strftime('%Y.%m.%d') + '.nc' for date in dates]
xr.save_mfdataset(datasets, filenames)
like image 199
jhamman Avatar answered Feb 18 '26 15:02

jhamman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!