Skip to content

Commit 27bccfc

Browse files
committed
Fix pydata#1040: diff dim argument should be optional
* {Dataset,DataArray}.diff dim argument defaults to last dimension * add test cases * add changelog
1 parent 6c90583 commit 27bccfc

File tree

5 files changed

+30
-4
lines changed

5 files changed

+30
-4
lines changed

doc/whats-new.rst

+5
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,11 @@ Bug fixes
137137
- Fixed sub-optimal performance in certain operations with object arrays (:issue:`1121`).
138138
By `Yves Delley <https://github.com/burnpanck>`_.
139139

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

142147
v0.8.2 (18 August 2016)

xarray/core/dataarray.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1460,13 +1460,14 @@ def _title_for_slice(self, truncate=50):
14601460

14611461
return title
14621462

1463-
def diff(self, dim, n=1, label='upper'):
1463+
def diff(self, dim=None, n=1, label='upper'):
14641464
"""Calculate the n-th order discrete difference along given axis.
14651465
14661466
Parameters
14671467
----------
14681468
dim : str, optional
1469-
Dimension over which to calculate the finite difference.
1469+
Dimension over which to calculate the finite difference. Defaults
1470+
to last dimension (like in ``diff`` in numpy).
14701471
n : int, optional
14711472
The number of times values are differenced.
14721473
label : str, optional

xarray/core/dataset.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -2111,13 +2111,14 @@ def _copy_attrs_from(self, other):
21112111
for v in other.variables:
21122112
self.variables[v].attrs = other.variables[v].attrs
21132113

2114-
def diff(self, dim, n=1, label='upper'):
2114+
def diff(self, dim=None, n=1, label='upper'):
21152115
"""Calculate the n-th order discrete difference along given axis.
21162116
21172117
Parameters
21182118
----------
21192119
dim : str, optional
2120-
Dimension over which to calculate the finite difference.
2120+
Dimension over which to calculate the finite difference. Defaults
2121+
to last dimension (like in ``diff`` in numpy).
21212122
n : int, optional
21222123
The number of times values are differenced.
21232124
label : str, optional
@@ -2156,6 +2157,10 @@ def diff(self, dim, n=1, label='upper'):
21562157
raise ValueError('order `n` must be non-negative but got {0}'
21572158
''.format(n))
21582159

2160+
# get default last dim if not specified
2161+
if dim is None:
2162+
dim = self.dims[-1]
2163+
21592164
# prepare slices
21602165
kwargs_start = {dim: slice(None, -1)}
21612166
kwargs_end = {dim: slice(1, None)}

xarray/test/test_dataarray.py

+8
Original file line numberDiff line numberDiff line change
@@ -2175,6 +2175,14 @@ def test_dataarray_diff_n1(self):
21752175
['x', 'y'])
21762176
self.assertDataArrayEqual(expected, actual)
21772177

2178+
def test_dataarray_diff_default_dim(self):
2179+
da = self.ds['foo']
2180+
actual = da.diff()
2181+
expected = DataArray(np.diff(da.values, axis=1),
2182+
[da['x'].values, da['y'].values[1:]],
2183+
['x', 'y'])
2184+
self.assertDataArrayEqual(expected, actual)
2185+
21782186
def test_coordinate_diff(self):
21792187
# regression test for GH634
21802188
arr = DataArray(range(0, 20, 2), dims=['lon'], coords=[range(10)])

xarray/test/test_dataset.py

+7
Original file line numberDiff line numberDiff line change
@@ -2878,6 +2878,13 @@ def test_dataset_diff_exception_label_str(self):
28782878
with self.assertRaisesRegexp(ValueError, '\'label\' argument has to'):
28792879
ds.diff('dim2', label='raise_me')
28802880

2881+
def test_dataset_diff_default_dim(self):
2882+
ds = Dataset({'foo': ('x', [5, 5, 6, 6])})
2883+
actual = ds.diff()
2884+
expected = Dataset({'foo': ('x', [0, 1, 0])})
2885+
expected.coords['x'].values = [1, 2, 3]
2886+
self.assertDatasetEqual(expected, actual)
2887+
28812888
def test_shift(self):
28822889
coords = {'bar': ('x', list('abc')), 'x': [-4, 3, 2]}
28832890
attrs = {'meta': 'data'}

0 commit comments

Comments
 (0)