Skip to content

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

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 14 commits into from
Oct 1, 2024
Merged
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
15 changes: 15 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,3 +1180,18 @@ 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():
# Create a DataFrame with a single column containing a Timedelta and NaT
Copy link
Member

Choose a reason for hiding this comment

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

The comments in this test repeat the code verbatim. Can you remove them.

In addition, can you add a reference to the issue as the first line of this test.

def test_groupby_any_with_timedelta():
    # GH#59712

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added these changes.

df = DataFrame({"value": [pd.Timedelta(1), pd.NaT]})

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

# Expected result: group with NaT should return False
expected = Series({0: True, 1: False}, name="value", dtype=bool)
expected.index = expected.index.astype(np.int64)

# Check if the result matches the expected output
tm.assert_series_equal(result, expected)