The Wayback Machine - http://web.archive.org/web/20201001231001/https://github.com/pydata/xarray/issues/3458
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep index dimension when selecting only a single coord #3458

Open
ngreenwald opened this issue Oct 29, 2019 · 5 comments
Open

Keep index dimension when selecting only a single coord #3458

ngreenwald opened this issue Oct 29, 2019 · 5 comments

Comments

@ngreenwald
Copy link

@ngreenwald ngreenwald commented Oct 29, 2019

MCVE Code Sample

# Your code here
import numpy as np
import xarray as xr

data = np.zeros((10, 4))
example_xr = xr.DataArray(data, coords=[range(10), ["idx0", "idx1", "idx2", "dim3"]], dims=["rows", "cols"])

# desired behavior
subset = example_xr[:, 1:2]
subset.shape

# inclusive indexing means both idx1 and idx2 kept
subset_named1 = example_xr.loc[:, "idx1":"idx2"]
subset_named1.shape

# slicing behavior means that 2nd dimension is dropped
subset_named2 = example_xr.loc[:, "idx1"]
subset_named2.shape

Expected Output

I'd like to be able to use named .loc indexing to select only a single named coord from one dimension, but not have that dimension collapse when subsetting.

Problem Description

I looked, but wasn't able to find anything in the documentation about how to perform this same action using named coords. It works with integer-based slicing.

Output of xr.show_versions()

# Paste the output here xr.show_versions() here
@mathause
Copy link
Collaborator

@mathause mathause commented Oct 29, 2019

I think example_xr.loc[:, ["idx1"]] should do what you want.

@dcherian
Copy link
Contributor

@dcherian dcherian commented Oct 29, 2019

We should add this as an example in the documentation since it comes up often enough.

@ngreenwald
Copy link
Author

@ngreenwald ngreenwald commented Oct 29, 2019

@max-sixty
Copy link
Collaborator

@max-sixty max-sixty commented Oct 29, 2019

Also example_xr.sel(cols=['idx1']) for the more idiomatic use of dim names

@NowanIlfideme
Copy link

@NowanIlfideme NowanIlfideme commented Nov 22, 2019

Note that this doesn't work on MultiIndex levels, since vectorized operations on them are not currently supported. Meanwhile, using sel(multiindex_level_name="a") drops the level from the multiindex entirely. The running theme is that this is dependent on #1603, it seems. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
5 participants
You can’t perform that action at this time.