Skip to content
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

BUG: groupby().any() returns true for groups with timedelta all NaT #59782

Merged
merged 14 commits into from
Oct 1, 2024
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,7 @@ Plotting
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
- Bug in :meth:`.DataFrameGroupBy.__len__` and :meth:`.SeriesGroupBy.__len__` would raise when the grouping contained NA values and ``dropna=False`` (:issue:`58644`)
- Bug in :meth:`.DataFrameGroupBy.any` that returned True for groups where all Timedelta values are NaT. (:issue:`59712`)
- Bug in :meth:`.DataFrameGroupBy.groups` and :meth:`.SeriesGroupby.groups` that would not respect groupby argument ``dropna`` (:issue:`55919`)
- Bug in :meth:`.DataFrameGroupBy.median` where nat values gave an incorrect result. (:issue:`57926`)
- Bug in :meth:`.DataFrameGroupBy.quantile` when ``interpolation="nearest"`` is inconsistent with :meth:`DataFrame.quantile` (:issue:`47942`)
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,10 @@ def _call_cython_op(

is_datetimelike = dtype.kind in "mM"

if self.how in ["any", "all"]:
if mask is None:
mask = isna(values)

if is_datetimelike:
values = values.view("int64")
is_numeric = True
Expand All @@ -380,12 +384,10 @@ def _call_cython_op(
values = values.astype(np.float32)

if self.how in ["any", "all"]:
if mask is None:
mask = isna(values)
if dtype == object:
if kwargs["skipna"]:
# GH#37501: don't raise on pd.NA when skipna=True
if mask.any():
if mask is not None and mask.any():
# mask on original values computed separately
values = values.copy()
values[mask] = True
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,3 +1180,15 @@ def test_grouping_by_key_is_in_axis():
result = gb.sum()
expected = DataFrame({"a": [1, 2], "b": [1, 2], "c": [7, 5]})
tm.assert_frame_equal(result, expected)


def test_groupby_any_with_timedelta():
# GH#59712
df = DataFrame({"value": [pd.Timedelta(1), pd.NaT]})

result = df.groupby(np.array([0, 1], dtype=np.int64))["value"].any()

expected = Series({0: True, 1: False}, name="value", dtype=bool)
expected.index = expected.index.astype(np.int64)

tm.assert_series_equal(result, expected)