Skip to content

Indexing with an empty array #2883

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

Merged
merged 4 commits into from
Apr 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ Enhancements
Bug fixes
~~~~~~~~~

- indexing with an empty list creates an object with zero-length axis (:issue:`2882`)
By `Mayeul d'Avezac <https://github.com/mdavezac>`_.

.. _whats-new.0.12.1:

v0.12.1 (4 April 2019)
Expand Down
4 changes: 3 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from distutils.version import LooseVersion
from numbers import Number
from typing import (
Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union)
Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union, Sequence)

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -1516,6 +1516,8 @@ def _validate_indexers(
v = as_variable(v)
elif isinstance(v, Dataset):
raise TypeError('cannot use a Dataset as an indexer')
elif isinstance(v, Sequence) and len(v) == 0:
v = IndexVariable((k, ), np.zeros((0,), dtype='int64'))
else:
v = np.asarray(v)

Expand Down
8 changes: 8 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,14 @@ def test_getitem_dataarray(self):
assert_equal(da[ind], da[[0, 1]])
assert_equal(da[ind], da[ind.values])

def test_getitem_empty_index(self):
da = DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y'])
assert_identical(da[{'x': []}],
DataArray(np.zeros((0, 4)), dims=['x', 'y']))
assert_identical(da.loc[{'y': []}],
DataArray(np.zeros((3, 0)), dims=['x', 'y']))
assert_identical(da[[]], DataArray(np.zeros((0, 4)), dims=['x', 'y']))

def test_setitem(self):
# basic indexing should work as numpy's indexing
tuples = [(0, 0), (0, slice(None, None)),
Expand Down