Skip to content
Closed
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
5 changes: 5 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ Bug fixes
- Fixed sub-optimal performance in certain operations with object arrays (:issue:`1121`).
By `Yves Delley <https://github.com/burnpanck>`_.

- Fixed default dim argument in ``.diff()`` methods to be truly optional (as in
docstring), defaults to last dimension (convenient for 1D arrays and
consistent with ``diff`` in numpy (:issue:`1040`).
By `Ondřej Grover <https://github.com/smartass101>`_.

.. _whats-new.0.8.2:

v0.8.2 (18 August 2016)
Expand Down
5 changes: 3 additions & 2 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1460,13 +1460,14 @@ def _title_for_slice(self, truncate=50):

return title

def diff(self, dim, n=1, label='upper'):
def diff(self, dim=None, n=1, label='upper'):
"""Calculate the n-th order discrete difference along given axis.

Parameters
----------
dim : str, optional
Dimension over which to calculate the finite difference.
Dimension over which to calculate the finite difference. Defaults
to last dimension (like in ``diff`` in numpy).
n : int, optional
The number of times values are differenced.
label : str, optional
Expand Down
9 changes: 7 additions & 2 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2111,13 +2111,14 @@ def _copy_attrs_from(self, other):
for v in other.variables:
self.variables[v].attrs = other.variables[v].attrs

def diff(self, dim, n=1, label='upper'):
def diff(self, dim=None, n=1, label='upper'):
"""Calculate the n-th order discrete difference along given axis.

Parameters
----------
dim : str, optional
Dimension over which to calculate the finite difference.
Dimension over which to calculate the finite difference. Defaults
to last dimension (like in ``diff`` in numpy).
n : int, optional
The number of times values are differenced.
label : str, optional
Expand Down Expand Up @@ -2156,6 +2157,10 @@ def diff(self, dim, n=1, label='upper'):
raise ValueError('order `n` must be non-negative but got {0}'
''.format(n))

# get default last dim if not specified
if dim is None:
dim = self.dims[-1]
Copy link
Member

Choose a reason for hiding this comment

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

This isn't going to work -- self.dims is an sorted dict on Dataset. Moreover, Dataset dims are actually always in sorted order, so the default isn't very sensible.

We could make the default dim be determined per variable, but that wouldn't work very well if different variables had different dimensions or dimension orders.

I think the simplest thing to do is to only allow omitting dim if the dataset has only one dimension.

Copy link
Author

Choose a reason for hiding this comment

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

Doing this only for 1D is possible, but would make the docstring somewhat less obvious.

Something like dim, optional for 1D ?

Copy link
Member

Choose a reason for hiding this comment

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

Sure.


# prepare slices
kwargs_start = {dim: slice(None, -1)}
kwargs_end = {dim: slice(1, None)}
Expand Down
8 changes: 8 additions & 0 deletions xarray/test/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2175,6 +2175,14 @@ def test_dataarray_diff_n1(self):
['x', 'y'])
self.assertDataArrayEqual(expected, actual)

def test_dataarray_diff_default_dim(self):
da = self.ds['foo']
actual = da.diff()
expected = DataArray(np.diff(da.values, axis=1),
[da['x'].values, da['y'].values[1:]],
['x', 'y'])
self.assertDataArrayEqual(expected, actual)

def test_coordinate_diff(self):
# regression test for GH634
arr = DataArray(range(0, 20, 2), dims=['lon'], coords=[range(10)])
Expand Down
7 changes: 7 additions & 0 deletions xarray/test/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2878,6 +2878,13 @@ def test_dataset_diff_exception_label_str(self):
with self.assertRaisesRegexp(ValueError, '\'label\' argument has to'):
ds.diff('dim2', label='raise_me')

def test_dataset_diff_default_dim(self):
ds = Dataset({'foo': ('x', [5, 5, 6, 6])})
actual = ds.diff()
expected = Dataset({'foo': ('x', [0, 1, 0])})
expected.coords['x'].values = [1, 2, 3]
self.assertDatasetEqual(expected, actual)

def test_shift(self):
coords = {'bar': ('x', list('abc')), 'x': [-4, 3, 2]}
attrs = {'meta': 'data'}
Expand Down