pydata / pydata/xarray

square-bracket slice a Dataset with a DataArray

Open
#2,027 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-indexing
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

Given this:

ds = xarray.Dataset(
    data_vars={
        'vote': ('pupil', [5, 7, 8]),
        'age': ('pupil', [15, 14, 16])
    },
    coords={
        'pupil': ['Alice', 'Bob', 'Charlie']
    })


<xarray.Dataset>
Dimensions:  (pupil: 3)
Coordinates:
  * pupil    (pupil) <U7 'Alice' 'Bob' 'Charlie'
Data variables:
    vote     (pupil) int64 5 7 8
    age      (pupil) int64 15 14 16

Why does this work:

ds.age[ds.vote >= 6]

<xarray.DataArray 'age' (pupil: 2)>
array([14, 16])
Coordinates:
  * pupil    (pupil) <U7 'Bob' 'Charlie'

But this doesn't?

ds[ds.vote >= 6]

KeyError: False

ds.vote >= 6 is a DataArray with dims=('pupil', ) and dtype=bool, so I can't think of any ambiguity in what I want to achieve?

Workaround:

ds.sel(pupil=ds.vote >= 6)


<xarray.Dataset>
Dimensions:  (pupil: 2)
Coordinates:
  * pupil    (pupil) <U7 'Bob' 'Charlie'
Data variables:
    vote     (pupil) int64 7 8
    age      (pupil) int64 14 16

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from Dataset square-bracket indexing and compare it with the shown DataArray indexing and Dataset.sel examples. Confirm that a boolean DataArray such as ds.vote >= 6 selects matching entries across the Dataset, and verify the result against the expected two-row Dataset output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.