Skip to content
Merged
12 changes: 6 additions & 6 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,12 @@ def _call_cython_op(
if values.dtype == "float16":
values = values.astype(np.float32)

values = values.T
if mask is not None:
mask = mask.T
if result_mask is not None:
result_mask = result_mask.T

if self.how in ["any", "all"]:
if mask is None:
mask = isna(values)
Expand All @@ -392,12 +398,6 @@ def _call_cython_op(
values = values.astype(bool, copy=False).view(np.int8)
is_numeric = True

values = values.T
if mask is not None:
mask = mask.T
if result_mask is not None:
result_mask = result_mask.T

out_shape = self._get_output_shape(ngroups, values)
func = self._get_cython_function(self.kind, self.how, values.dtype, is_numeric)
values = self._get_cython_vals(values)
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,3 +1180,28 @@ 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 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 with sorting enabled and check if any Timedelta exists
result = df.groupby("A", sort=True)["B"].any()

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

# Set the expected index name to match the result
expected.index.name = "A"

# Sort the expected result to match the order of result
expected = expected.sort_index()

# Assert that the result matches the expected output
tm.assert_series_equal(result, expected)
Loading