Skip to content

FIX DataFrame diff with timedelta #7280

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

Closed
wants to merge 1 commit into from
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
3 changes: 2 additions & 1 deletion pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,8 @@ def diff(arr, n, axis=0):
na_indexer[axis] = slice(None, n) if n >= 0 else slice(n, None)
out_arr[tuple(na_indexer)] = na

if arr.ndim == 2 and arr.dtype.name in _diff_special:
if (arr.ndim == 2 and arr.dtype.name in _diff_special
Copy link
Contributor

Choose a reason for hiding this comment

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

actually I would do this slightly differently. I would define the dtype of out_arr (as the same as the input type), except for datetime64[ns], then I think you can use this as is.

and dtype != 'timedelta64[ns]'):
f = _diff_special[arr.dtype.name]
f(arr, out_arr, n, axis)
else:
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9285,6 +9285,16 @@ def test_diff_float_n(self):
xp = self.tsframe.diff(1)
assert_frame_equal(rs, xp)

def test_diff_timedelta(self):
df = DataFrame(dict(time=[Timestamp('20130101 9:01'),
Timestamp('20130101 9:02')],
value=[1.0,2.0]))
res = df.diff()
exp = DataFrame([[pd.NaT, np.nan],
[np.timedelta64(int(6e10), 'ns'), 1]],
columns=['time', 'value'])
assert_frame_equal(res, exp)

def test_pct_change(self):
rs = self.tsframe.pct_change(fill_method=None)
assert_frame_equal(rs, self.tsframe / self.tsframe.shift(1) - 1)
Expand Down