Skip to content

Get 0d slices of ndarrays directly from indexing #2625

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 3 commits into from
Dec 22, 2018
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 @@ -56,6 +56,9 @@ Enhancements
- :py:meth:`DataArray.resample` and :py:meth:`Dataset.resample` now supports the
``loffset`` kwarg just like Pandas.
By `Deepak Cherian <https://github.com/dcherian>`_
- 0d slices of ndarrays are now obtained directly through indexing, rather than
extracting and wrapping a scalar, avoiding unnecessary copying. By `Daniel
Wennberg <https://github.com/danielwe>`_.

Bug fixes
~~~~~~~~~
Expand Down
16 changes: 5 additions & 11 deletions xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1142,15 +1142,6 @@ def __init__(self, array):
'Trying to wrap {}'.format(type(array)))
self.array = array

def _ensure_ndarray(self, value):
# We always want the result of indexing to be a NumPy array. If it's
# not, then it really should be a 0d array. Doing the coercion here
# instead of inside variable.as_compatible_data makes it less error
# prone.
if not isinstance(value, np.ndarray):
value = utils.to_0d_array(value)
return value

def _indexing_array_and_key(self, key):
if isinstance(key, OuterIndexer):
array = self.array
Expand All @@ -1160,7 +1151,10 @@ def _indexing_array_and_key(self, key):
key = key.tuple
elif isinstance(key, BasicIndexer):
array = self.array
key = key.tuple
# We want 0d slices rather than scalars. This is achieved by
# appending an ellipsis (see
# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#detailed-notes). # noqa
key = key.tuple + (Ellipsis,)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two questions:

  1. does this also work in the other branches, i.e., the ones that do fancy indexing?
  2. (related) can you remove the _ensure_ndarray method above?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. It does not affect outer indexing but breaks vectorized indexing, where some arrays come back with dimensions in a different order. I haven't looked into exactly why. It would be nice to move the change into __getitem__, as return array[key + (Ellipsis,)], but I'm afraid that won't work. In any case, I think only basic indexing ever returns a 0d array, so the current change covers all relevant cases.

  2. In fact, yes. I was convinced there were edge cases with object arrays etc., so I let it stay, but all tests pass without. Removed now.

else:
raise TypeError('unexpected key type: {}'.format(type(key)))

Expand All @@ -1171,7 +1165,7 @@ def transpose(self, order):

def __getitem__(self, key):
array, key = self._indexing_array_and_key(key)
return self._ensure_ndarray(array[key])
return array[key]

def __setitem__(self, key, value):
array, key = self._indexing_array_and_key(key)
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,11 @@ def test_getitem_basic(self):
assert v_new.dims == ('x', )
assert_array_equal(v_new, v._data[:, 1])

# test that we obtain a modifiable view when taking a 0d slice
v_new = v[0, 0]
v_new[...] += 99
assert_array_equal(v_new, v._data[0, 0])

def test_getitem_with_mask_2d_input(self):
v = Variable(('x', 'y'), [[0, 1, 2], [3, 4, 5]])
assert_identical(v._getitem_with_mask(([-1, 0], [1, -1])),
Expand Down