diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt old mode 100644 new mode 100755 index 352f079f38e96..29368d66b2991 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -18,6 +18,7 @@ Enhancements ~~~~~~~~~~~~ - Added ``StringMethods.capitalize()`` and ``swapcase`` which behave as the same as standard ``str`` (:issue:`9766`) +- ``DataFrame.diff`` now takes an ``axis`` parameter that determines the direction of differencing (:issue:`9727`) - Added ``StringMethods`` (.str accessor) to ``Index`` (:issue:`9068`) The `.str` accessor is now available for both `Series` and `Index`. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 19f15f58afffd..a02fa3b9e3674 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3584,7 +3584,7 @@ def unstack(self, level=-1): #---------------------------------------------------------------------- # Time series-related - def diff(self, periods=1): + def diff(self, periods=1, axis=0): """ 1st discrete difference of object @@ -3592,12 +3592,14 @@ def diff(self, periods=1): ---------- periods : int, default 1 Periods to shift for forming difference + axis : {0 or 'index', 1 or 'columns'}, default 0 Returns ------- diffed : DataFrame """ - new_data = self._data.diff(n=periods) + bm_axis = self._get_block_manager_axis(axis) + new_data = self._data.diff(n=periods, axis=bm_axis) return self._constructor(new_data) #---------------------------------------------------------------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 4d0f8394fbd2a..142a565077fbf 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -869,9 +869,9 @@ def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): def get_values(self, dtype=None): return self.values - def diff(self, n): + def diff(self, n, axis=1): """ return block for the diff of the values """ - new_values = com.diff(self.values, n, axis=1) + new_values = com.diff(self.values, n, axis=axis) return [make_block(values=new_values, ndim=self.ndim, fastpath=True, placement=self.mgr_locs)] diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index c7c35e63d3d91..467f6c60ac29b 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -10047,6 +10047,12 @@ def test_diff_float_n(self): xp = self.tsframe.diff(1) assert_frame_equal(rs, xp) + def test_diff_axis(self): + # GH 9727 + df = DataFrame([[1., 2.], [3., 4.]]) + assert_frame_equal(df.diff(axis=1), DataFrame([[np.nan, 1.], [np.nan, 1.]])) + assert_frame_equal(df.diff(axis=0), DataFrame([[np.nan, np.nan], [2., 2.]])) + def test_pct_change(self): rs = self.tsframe.pct_change(fill_method=None) assert_frame_equal(rs, self.tsframe / self.tsframe.shift(1) - 1)