how to select subset of data in a dataset using xarray

Solutions on MaxInterview for how to select subset of data in a dataset using xarray by the best coders in the world

showing results for - "how to select subset of data in a dataset using xarray"
Emely
21 Mar 2018
1#import xarray
2import xarray as xr
3
4#open the dataset
5ds = xr.open_dataset(file_name.nc)
6
7#get a subset of the data
8ds.sel(dim=slice()) # input the dimension (dim) to select and the value of the dimension into the slice function(slice)
9ds.loc[{'dim': slice()}]
10ds.where(bool array) #locate the values based on a condition
11
12#examples
13ds[var_name].loc[{'latitude': slice(60,48),
14                  'longitude': slice(-12,5)}]
15
16ds.where(ds[var_name] > 0.1)
17#the example will return a subset of the dataset where the latitude
18#and longitude are of the requirements stated in the slice function
19
Julián
01 Jan 2020
1#import xarray
2import xarray as xr
3
4#open the dataset
5ds = xr.open_dataset(file_name.nc)
6
7#var_name in the following table is to be entered as a string
8
9selection         |    syntax                     |    returns
10--------------------------------------------------------------
11single variable   | ds[var_name]                  | DataArray
12--------------------------------------------------------------
13single variable   | ds[[var_name]]                | Dataset
14--------------------------------------------------------------
15multiple variable | ds[[var_name1, var_name2...]] | Dataset
16
17