Skip to content

Commit 3354059

Browse files
mdavezacshoyer
authored andcommitted
Indexing with an empty array (#2883)
* Indexing with an empty array Closes #2882 * Adds 2882 resolution to whats-new.rst * Create empty indexing array directly * assert xxx -> asset_identical
1 parent a4305e7 commit 3354059

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Enhancements
2424
Bug fixes
2525
~~~~~~~~~
2626

27+
- indexing with an empty list creates an object with zero-length axis (:issue:`2882`)
28+
By `Mayeul d'Avezac <https://github.com/mdavezac>`_.
29+
2730
.. _whats-new.0.12.1:
2831

2932
v0.12.1 (4 April 2019)

xarray/core/dataset.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from distutils.version import LooseVersion
99
from numbers import Number
1010
from typing import (
11-
Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union)
11+
Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union, Sequence)
1212

1313
import numpy as np
1414
import pandas as pd
@@ -1516,6 +1516,8 @@ def _validate_indexers(
15161516
v = as_variable(v)
15171517
elif isinstance(v, Dataset):
15181518
raise TypeError('cannot use a Dataset as an indexer')
1519+
elif isinstance(v, Sequence) and len(v) == 0:
1520+
v = IndexVariable((k, ), np.zeros((0,), dtype='int64'))
15191521
else:
15201522
v = np.asarray(v)
15211523

xarray/tests/test_dataarray.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,14 @@ def test_getitem_dataarray(self):
501501
assert_equal(da[ind], da[[0, 1]])
502502
assert_equal(da[ind], da[ind.values])
503503

504+
def test_getitem_empty_index(self):
505+
da = DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y'])
506+
assert_identical(da[{'x': []}],
507+
DataArray(np.zeros((0, 4)), dims=['x', 'y']))
508+
assert_identical(da.loc[{'y': []}],
509+
DataArray(np.zeros((3, 0)), dims=['x', 'y']))
510+
assert_identical(da[[]], DataArray(np.zeros((0, 4)), dims=['x', 'y']))
511+
504512
def test_setitem(self):
505513
# basic indexing should work as numpy's indexing
506514
tuples = [(0, 0), (0, slice(None, None)),

0 commit comments

Comments
 (0)