Skip to content

Commit

Permalink
Ensures drop=True case works with empty mask (#1342)
Browse files Browse the repository at this point in the history
* Added test for where(mask, drop=True) [mask empty]

Ensures ds.where(mask, drop=True) works when the mask
is empty.

* Fix .get_index() for size 0 dimensions

This resolves issues with `where` with
`drop=True` with empty mask.
  • Loading branch information
pwolfram authored and shoyer committed Apr 2, 2017
1 parent c0178b7 commit 56cec46
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ Bug fixes
- Fix ``sel`` with ``method='nearest'`` on Python 2.7 and 64-bit Windows
(:issue:`1140`).
`Stephan Hoyer <https://github.com/shoyer>`_.
- Fixes ``where`` with ``drop='True'`` for empty masks (:issue:`1341`).
By `Stephan Hoyer <https://github.com/shoyer>`_ and
`Phillip J. Wolfram <https://github.com/pwolfram>`_.

.. _whats-new.0.9.1:

Expand Down
3 changes: 2 additions & 1 deletion xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,8 @@ def get_index(self, key):
try:
return self.indexes[key]
except KeyError:
return pd.Index(range(self.sizes[key]), name=key)
# need to ensure dtype=int64 in case range is empty on Python 2
return pd.Index(range(self.sizes[key]), name=key, dtype=np.int64)

def _calc_assign_results(self, kwargs):
results = SortedKeysDict()
Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ def test_get_index(self):
with self.assertRaises(KeyError):
array.get_index('z')

def test_get_index_size_zero(self):
array = DataArray(np.zeros((0,)), dims=['x'])
actual = array.get_index('x')
expected = pd.Index([], dtype=np.int64)
assert actual.equals(expected)
assert actual.dtype == expected.dtype

def test_struct_array_dims(self):
"""
This test checks subraction of two DataArrays for the case
Expand Down
9 changes: 9 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2659,6 +2659,15 @@ def test_where_drop(self):
actual = ds.where(ds > 0, drop=True)
self.assertDatasetIdentical(expected, actual)

def test_where_drop_empty(self):
# regression test for GH1341
array = DataArray(np.random.rand(100, 10),
dims=['nCells', 'nVertLevels'])
mask = DataArray(np.zeros((100,), dtype='bool'), dims='nCells')
actual = array.where(mask, drop=True)
expected = DataArray(np.zeros((0, 10)), dims=['nCells', 'nVertLevels'])
self.assertDatasetIdentical(expected, actual)

def test_reduce(self):
data = create_test_data()

Expand Down

0 comments on commit 56cec46

Please sign in to comment.