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
7 changes: 7 additions & 0 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,13 @@ def _call_cython_op(
if is_datetimelike:
values = values.view("int64")
is_numeric = True

# Fix for NaT handling: ensure NaT is treated as False in any() and all()
if self.how in ["any", "all"]:
# Set NaT (which is represented as the smallest int64) to False (0)
nat_mask = values == np.iinfo(np.int64).min
values[nat_mask] = 0 # Treat NaT as False
Copy link
Member

Choose a reason for hiding this comment

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

The linked issue suggests moving up the determination of mask below to be prior to viewing the values as int64 on L375. Is there a reason this doesn't work?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sorry, it appears i went in the wrong direction with my implementation. Just did a commit with this better solution. Could you give me some pointers on all these check failures?


elif dtype.kind == "b":
values = values.view("uint8")
if values.dtype == "float16":
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,3 +1180,19 @@ 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(self):
# Create a DataFrame with Timedelta and NaT values
df = DataFrame({
"A": ["foo", "foo", "bar", "bar"],
"B": [pd.Timedelta(1, unit='D'), pd.NaT, pd.Timedelta(2, unit='D'), pd.NaT]
})

# Group by column A and check if any Timedelta exists (i.e., non-NaT)
result = df.groupby("A")["B"].any()

# Expected result: groups with only NaT should return False, others should return True
expected = Series([True, False], index=["foo", "bar"], name="B")

tm.assert_series_equal(result, expected)
Loading