pydata / pydata/xarray

(i)loc slicer specialization for convenient slicing by dimension label as `.loc('dim_name')[:n]`

Open
#8,992 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Is your feature request related to a problem?

Until PEP 472, I'm sure we would all love to be able to do indexing with labeled dimension names inside brackets. Here I'm proposing a slightly modified syntax which is possible to implement and would be quite convenient IMHO.

Describe the solution you'd like

This is inspired by the Pandas .loc(axis=n) specialization. Essentially the .(i)loc accessors would become callable like in Pandas, which would enable to specify the desired order of dimensions in the subsequent slicing brackets. Schematically

darr.loc('dim name 1', 'dim name 2')[x1:x2,y1:y2]

is equivalent to first returning an augmented _LocIndexer which now associates positional indexes to according to the provided dim order

loc_idx_spec = darr.loc('dim name 1', 'dim name 2')
loc_idx_spec[x1:x2,y1:y2]

The first part is essentially similar to .transpose('dim name 1', 'dim name 2') and in the case of a DataArray it could be used instead. But this syntax could work also for Dataset. Additonally, it does not require an actual transpose operation.

This accessor becomes especially convenient when you quickly want to index just one dimension such as

darr.loc('dim name')[:x2]
Describe alternatives you've considered

The equivalent darr.sel({'dim name 1': slice(x1, x2), 'dim name 2': slice(y1,y2)}) is admittedly not that much worse, but for me writing slice feels cumbersome especially in situations when you have a lot of None specifications such as slice(None,None,2).

Additional context

This .loc(axis=n) API is (not so obviously) documented for Pandas here.

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

Read the current .loc and .iloc accessor entry points, then compare their behavior with the documented Pandas .loc(axis=n) slicer and the existing sel and transpose alternatives. Define and test callable dimension-ordering behavior, including one-dimension slicing, with completion shown by tests covering the examples in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
pandas, python
Domain
data
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.