Skip to main content
Geosciences LibreTexts

17.3: Selecting values

  • Page ID
    24684
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    If you have the following DataArray:

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

    data = np.array([[22, 20, 18], [18, 16, 14], [30, 32, 34]])
    times = pd.date_range("2023-01-01", periods=3, freq='D')
    cities = ['New York', 'London', 'Mumbai']

    temperature_data_array = xr.DataArray(data, coords=[cities, times], dims=['city', 'time'])

    You can access the data in an Xarray using labels, much like you would in a Pandas Series, using .loc[] and .iloc[]

    .loc[] uses labels, so you could access elements this way:

    temperature_data_array.loc['New York','2023-01-02'] would return a value of 20.  One issue here is that you have to know the order of the labels; if you reverse the order of labels, e.g.,temperature_data_array.loc['2023-01-02','New York'], this will generate an error.

    The .iloc[] command works exactly the same way, using the integer position to access the values.  For example, we can access the same point (New York on 2023-01-02) with this command:

    temperature_data_array.iloc[0,1]

    A more common and convenient way of selecting parts of a DataArray is with the .sel() method:

    temperature_data_array.sel(city='New York', time='2023-01-02')

    This yields the same data point.  There is also an .isel() method, which uses the index number to access the array:

    temperature_data_array.isel(city=0, time=1)

    This selects the same point, New York (element zero) and 2023-01-02 (element 1).  This would retrieve the same data point as all the previous examples.

    Note that .sel() and .isel() can be considered analogous to .loc[] and .iloc[].

    What if you want to get a range of points?  You can use the slice() function with .sel() and .isel().  As an example, let's define a DataArray ds:

    # Define the dimensions

    latitudes = np.linspace(-90, 90, 181)  # 181 points from -90 to 90 degrees
    longitudes = np.linspace(-180, 180, 361)  # 361 points from -180 to 180 degrees
    times = pd.date_range('2023-01-01', periods=10, freq='D')  # 10 days of data

    # Create a 3D array of random data
    data = np.random.rand(len(times), len(latitudes), len(longitudes))

    # Create the DataArray
    ds = xr.DataArray(data, coords=[('time', times), ('lat', latitudes), ('lon', longitudes)])

    Now let's pretend we want to select data for latitudes from -45 to 45, and for the first five days of January 2023.

    selected_data = ds.sel(lat=slice(-45, 45), time=slice('2023-01-01', '2023-01-05'))

    This will yield a subset of the original DataArray 'ds' that is confined to the specified latitude and time slices.  Since we don't including any slicing for longitudes, the resulting DataArray includes all longitudes.

    To slice from the beginning or to the end of the array, use None as the endpoint.  For example, if we want all latitudes from the beginning of the latitudes up to 45, we would use the command slice(None,45).  If you want latitudes starting at 45 and going to the end of the latitudes, use the command slice(45,None)

    You can also use this with .isel().  For example, if we want elements 3 through 8 of latitudes and 2 through 5 of longitudes, we could use this syntax:

    selected_data = ds.isel(lat=slice(3,9), lon=slice(2,6))

    Note that our .isel() slice indices have an end number that is one larger than what we want: if we want elements 3-8, we need to slice(3,9).  This only applies to .isel(); for .sel(), the end value of the slice is included in the extracted data.


    17.3: Selecting values is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?