Xarray: The best way to select data variables from DataSet

Created on 28 Dec 2017  路  1Comment  路  Source: pydata/xarray

Selecting data variables from DataSet

Here is my code for selecting a set of data variables from a DataSet. Is this the best way to do it?

Code Sample. See get function at the end.

import numpy as np
import pandas as pd
import xarray as xr

temp = 15 + 8 * np.random.randn(2, 2, 3)
precip = 10 * np.random.rand(2, 2, 3)
pressure = 1000 + np.random.randn(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]

ds = xr.Dataset({'temperature': (['x', 'y', 'time'],  temp),
                 'precipitation': (['x', 'y', 'time'], precip),
                 'pressure': (['x', 'y', 'time'], pressure)},
                 coords={'lon': (['x', 'y'], lon),
                         'lat': (['x', 'y'], lat),
                         'time': pd.date_range('2014-09-06', periods=3),
                         'reference_time': pd.Timestamp('2014-09-05')})

# get the precipitation and presseure
ds.get(['precipitation', 'pressure'])

Output

<xarray.Dataset>
Dimensions:         (time: 3, x: 2, y: 2)
Coordinates:
    lon             (x, y) float64 -99.83 -99.32 -99.79 -99.23
    lat             (x, y) float64 42.25 42.21 42.63 42.59
  * time            (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
    reference_time  datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
    precipitation   (x, y, time) float64 4.762 4.104 0.02204 3.794 7.735 ...
    pressure        (x, y, time) float64 998.8 1.001e+03 1.001e+03 1e+03 ...

Output of xr.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_GB.UTF-8
LOCALE: None.None

xarray: 0.10.0
pandas: 0.20.3+0.g3a7f956c3.dirty
numpy: 1.13.3
scipy: 0.19.1
netCDF4: 1.3.1
h5netcdf: None
Nio: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
matplotlib: 2.0.2
cartopy: None
seaborn: 0.8.1
setuptools: 27.2.0
pip: 9.0.1
conda: None
pytest: None
IPython: 6.1.0
sphinx: None

usage question

Most helpful comment

You can also use the following dict-like syntax using a list of variable names:

ds[['precipitation', 'pressure']]

This question was also recently asked on Stack Overflow: https://stackoverflow.com/a/47334689/1757464

>All comments

You can also use the following dict-like syntax using a list of variable names:

ds[['precipitation', 'pressure']]

This question was also recently asked on Stack Overflow: https://stackoverflow.com/a/47334689/1757464

Was this page helpful?
0 / 5 - 0 ratings