How to select data in a rectangular box from xarray data?

  Data, Numpy, Python

Xarray data is often used in huge spatial datasets. We often need to fetch data in subregions. The following example shows you how to extract subset data from a large xarray.

import numpy as np
import xarray as xr

#set the sub domain box

min_lon = 100 
min_lat = 20
max_lon = 150
max_lat = 40

# read xarray data
fn='testfile.nc4'
ds=xr.open_dataset(fn,decode_times=False) #decode_times=True|False
cropped_ds = ds.sel(lat=slice(min_lat,max_lat), lon=slice(min_lon,max_lon))

#note: slice(min_lat,max_lat) or slice(max_lat,min_lat) depends on how your data is saved in the file. If data is saved from north to south, you should use slice(max_lat,min_lat)