Skip to content

Instantly share code, notes, and snippets.

@tommylees112
Last active August 19, 2021 15:17
Show Gist options
  • Save tommylees112/f61b0dc1481f8d977916f6d1f0cbcff9 to your computer and use it in GitHub Desktop.
Save tommylees112/f61b0dc1481f8d977916f6d1f0cbcff9 to your computer and use it in GitHub Desktop.
Getting started with netcdf data using xarray
# conda install -c conda-forge xarray --yes
import xarray as xr
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
data_dir = Path("path/to/data")
# open the data
dynamic = xr.open_dataset(data_dir / "ALL_dynamic_ds.nc")
static = xr.open_dataset(data_dir / "camels_static.nc")
# select individual stations, e.g. Thames at Kingston = 39001 is the station code
thames = dynamic.sel(station_id=39001)
# select and plot discharge and precipitation
f, axs = plt.subplots(2, 1, figsize=(12, 4))
axs[0].plot(thames["time"], thames["discharge_spec"])
axs[1].plot(thames["time"], thames["precipitation"])
# convert to pandas (if you prefer)
df = thames.to_dataframe()
# NOTE: all the data inside the xarray.Dataset is a numpy array
np_discharge = dynamic.sel(station_id=39001, time="2007")["discharge_spec"].values
np_discharge.shape
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment