Skip to content

BUG: Series[td64].sum() wrong on empty series, closes #37151 #37394

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 1 commit into from
Oct 26, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ Datetimelike
- Bug in :class:`DatetimeIndex.shift` incorrectly raising when shifting empty indexes (:issue:`14811`)
- :class:`Timestamp` and :class:`DatetimeIndex` comparisons between timezone-aware and timezone-naive objects now follow the standard library ``datetime`` behavior, returning ``True``/``False`` for ``!=``/``==`` and raising for inequality comparisons (:issue:`28507`)
- Bug in :meth:`DatetimeIndex.equals` and :meth:`TimedeltaIndex.equals` incorrectly considering ``int64`` indexes as equal (:issue:`36744`)
- Bug in :meth:`TimedeltaIndex.sum` and :meth:`Series.sum` with ``timedelta64`` dtype on an empty index or series returning ``NaT`` instead of ``Timedelta(0)`` (:issue:`31751`)

Timedelta
^^^^^^^^^
Expand Down
18 changes: 7 additions & 11 deletions pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,14 +381,12 @@ def sum(
nv.validate_sum(
(), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial)
)
if not self.size and (self.ndim == 1 or axis is None):
return NaT

result = nanops.nansum(
self._data, axis=axis, skipna=skipna, min_count=min_count
self._ndarray, axis=axis, skipna=skipna, min_count=min_count
)
if is_scalar(result):
return Timedelta(result)
if axis is None or self.ndim == 1:
return self._box_func(result)
return self._from_backing_data(result)

def std(
Expand All @@ -403,13 +401,11 @@ def std(
nv.validate_stat_ddof_func(
(), dict(dtype=dtype, out=out, keepdims=keepdims), fname="std"
)
if not len(self):
return NaT
if not skipna and self._hasnans:
return NaT

result = nanops.nanstd(self._data, axis=axis, skipna=skipna, ddof=ddof)
return Timedelta(result)
result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)
if axis is None or self.ndim == 1:
return self._box_func(result)
return self._from_backing_data(result)

# ----------------------------------------------------------------
# Rendering Methods
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def _maybe_get_mask(
# Boolean data cannot contain nulls, so signal via mask being None
return None

if skipna:
if skipna or needs_i8_conversion(values.dtype):
mask = isna(values)

return mask
Expand Down
16 changes: 15 additions & 1 deletion pandas/tests/arrays/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pytest

import pandas as pd
from pandas import Timedelta
import pandas._testing as tm
from pandas.core.arrays import TimedeltaArray

Expand Down Expand Up @@ -175,7 +176,7 @@ def test_neg_freq(self):


class TestReductions:
@pytest.mark.parametrize("name", ["sum", "std", "min", "max", "median"])
@pytest.mark.parametrize("name", ["std", "min", "max", "median"])
@pytest.mark.parametrize("skipna", [True, False])
def test_reductions_empty(self, name, skipna):
tdi = pd.TimedeltaIndex([])
Expand All @@ -187,6 +188,19 @@ def test_reductions_empty(self, name, skipna):
result = getattr(arr, name)(skipna=skipna)
assert result is pd.NaT

@pytest.mark.parametrize("skipna", [True, False])
def test_sum_empty(self, skipna):
tdi = pd.TimedeltaIndex([])
arr = tdi.array

result = tdi.sum(skipna=skipna)
assert isinstance(result, Timedelta)
assert result == Timedelta(0)

result = arr.sum(skipna=skipna)
assert isinstance(result, Timedelta)
assert result == Timedelta(0)

def test_min_max(self):
arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"])

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/series/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ def test_reductions_td64_with_nat():
assert ser.max() == exp


@pytest.mark.parametrize("skipna", [True, False])
def test_td64_sum_empty(skipna):
# GH#37151
ser = Series([], dtype="timedelta64[ns]")

result = ser.sum(skipna=skipna)
assert isinstance(result, pd.Timedelta)
assert result == pd.Timedelta(0)


def test_td64_summation_overflow():
# GH#9442
ser = Series(pd.date_range("20130101", periods=100000, freq="H"))
Expand Down