Reading netcdf files with python (xarray basics)
Turning climate data files into insights without headaches
Reading netcdf files with python (xarray basics)
Turning climate data files into insights without headaches
Why netcdf matters in climate and hydrology?
Photo by Robert Lukeman on Unsplash
NetCDF (Network Common Data Form) is the go-to format for storing and sharing multidimensional scientific data. If you’ve ever downloaded CORDEX climate projections, CMIP6 datasets, ERA5 reanalysis, or hydrological model outputs, chances are they came in NetCDF format. It’s designed for efficiency, self-describing metadata, and portability — meaning your data comes with information about units, coordinates, calendar type, and more, all in the same file.
For example instead of juggling multiple CSV files for temperature, coordinates, and time, a NetCDF stores them all together with context. It’s like a zip archive and a database rolled into one.
Xarray… what?
xarray is a Python library built to handle labelled multidimensional arrays. Think of it as pandas for multi-dimensional data.
To install it:
pip install xarray netcdf4
*netcdf4enables full NetCDF reading/writing support. You can also installh5netcdfas an alternative backend.*
Opening a netcdf file
import xarray as xr
ds = xr.open_dataset("example.nc")
print(ds)
what’s happening here?
xr.open_dataset() lazily loads the file — it reads the metadata immediately but doesn’t pull the entire dataset into memory until needed.
The printed summary shows:
- Dimensions: e.g.,
time: 360, lat: 128, lon: 256 - Coordinates: arrays like
lat,lon,time - Data variables: e.g.,
tas(temperature at surface) - Attributes: metadata such as
units,title,source
Inspecting the data
print(ds.data_vars) # list all variables
print(ds.coords) # list coordinates
print(ds.attrs) # view global metadata
print(ds['tas']) # view variable metadata
do:
- Check units before analysis — precipitation might be in
kg m-2 s-1instead ofmm/day. - Check the
calendarattribute in time coordinates (important for climate datasets).
don’t:
- Assume variable names are always the same — different datasets may use
temp,tas, ort2mfor temperature.
Selecting subsets
# spatial subset
subset = ds.sel(lat=slice(45, 48), lon=slice(0, 5))
# temporal subset
subset_time = ds.sel(time=slice("2000-01-01", "2010-12-31"))
# combined
subset_both = ds.sel(lat=slice(45, 48), lon=slice(0, 5), time=slice("2000", "2010"))
Why this matters?
Climate data files are often huge — extracting only the region and period you need speeds up processing and saves memory.
[embed]Why Python and R for hydro-climatic studies? 2025 editionmedium.com
Computing statistics
# mean over time
mean_map = ds['tas'].mean(dim="time")
# mean over space
mean_series = ds['tas'].mean(dim=["lat", "lon"])
For big datasets, add chunks={"time": 12} when opening to enable Dask parallel processing.
Saving results
mean_map.to_netcdf("mean_temperature_map.nc")
do:
- Always include compression to save space:
mean_map.to_netcdf("mean_temperature_map.nc", encoding={"tas": {"zlib": True, "complevel": 4}})
don’t:
- Overwrite original files — keep raw data untouched for reproducibility.
Reading cordex temperature data
import xarray as xr
# open cordex data with chunking for performance
ds = xr.open_dataset("cordex_tas_EUR-11.nc", chunks={"time": 24})
# subset to France region
france_ds = ds.sel(lat=slice(42, 51), lon=slice(-5, 9))
# compute monthly mean time series
monthly_tas = france_ds['tas'].resample(time="M").mean()
# save results
monthly_tas.to_netcdf("france_monthly_tas.nc", encoding={"tas": {"zlib": True, "complevel": 4}})
Why it works well?
- chunks: avoids loading the entire dataset into memory.
- subset early: keeps only the spatial window you need.
- compression: reduces file size without losing data quality.
final checklist
- inspect variables, coordinates, and attributes before processing
- subset data early
- use chunking for large datasets
- keep raw files intact
- document your steps for reproducibility
Working with climate and hydrological datasets in NetCDF format doesn’t have to be intimidating. With xarray, you can open, explore, subset, and analyze multidimensional data efficiently — without drowning in memory issues or endless preprocessing.
By inspecting metadata first, selecting only the region and time period you need, using chunking for large files, and keeping raw data untouched, you set yourself up for clean, reproducible workflows. Whether you’re extracting temperature trends over a study area or generating global climate summaries, these practices turn massive datasets into meaningful insights with minimal friction.
Happy coding!

메타데이터
- post_id
- 751aa020557b
- slug
- reading-netcdf-files-with-python-xarray-basics-751aa020557b
- url
- https://levelup.gitconnected.com/reading-netcdf-files-with-python-xarray-basics-751aa020557b
- canonical_url
- https://levelup.gitconnected.com/reading-netcdf-files-with-python-xarray-basics-751aa020557b
- author_url
- https://medium.com/@katygenuine
- status
- ok
- fetched_at
- 2026-07-18 06:29:01