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: Avoid casting to float for datetimelike in min/max reductions #60850

Merged
merged 2 commits into from
Feb 5, 2025
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/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,7 @@ Datetimelike
- Bug in :func:`date_range` where using a negative frequency value would not include all points between the start and end values (:issue:`56147`)
- Bug in :func:`tseries.api.guess_datetime_format` would fail to infer time format when "%Y" == "%H%M" (:issue:`57452`)
- Bug in :func:`tseries.frequencies.to_offset` would fail to parse frequency strings starting with "LWOM" (:issue:`59218`)
- Bug in :meth:`DataFrame.min` and :meth:`DataFrame.max` casting ``datetime64`` and ``timedelta64`` columns to ``float64`` and losing precision (:issue:`60850`)
- Bug in :meth:`Dataframe.agg` with df with missing values resulting in IndexError (:issue:`58810`)
- Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` does not raise on Custom business days frequencies bigger then "1C" (:issue:`58664`)
- Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` returning ``False`` on double-digit frequencies (:issue:`58523`)
Expand Down
11 changes: 9 additions & 2 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1093,11 +1093,14 @@ def reduction(
if values.size == 0:
return _na_for_min_count(values, axis)

dtype = values.dtype
values, mask = _get_values(
values, skipna, fill_value_typ=fill_value_typ, mask=mask
)
result = getattr(values, meth)(axis)
result = _maybe_null_out(result, axis, mask, values.shape)
result = _maybe_null_out(
result, axis, mask, values.shape, datetimelike=dtype.kind in "mM"
)
return result

return reduction
Expand Down Expand Up @@ -1499,6 +1502,7 @@ def _maybe_null_out(
mask: npt.NDArray[np.bool_] | None,
shape: tuple[int, ...],
min_count: int = 1,
datetimelike: bool = False,
) -> np.ndarray | float | NaTType:
"""
Returns
Expand All @@ -1520,7 +1524,10 @@ def _maybe_null_out(
null_mask = np.broadcast_to(below_count, new_shape)

if np.any(null_mask):
if is_numeric_dtype(result):
if datetimelike:
# GH#60646 For datetimelike, no need to cast to float
result[null_mask] = iNaT
elif is_numeric_dtype(result):
if np.iscomplexobj(result):
result = result.astype("c16")
elif not is_float_dtype(result):
Expand Down
38 changes: 38 additions & 0 deletions pandas/tests/frame/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1544,6 +1544,44 @@ def test_min_max_dt64_with_NaT(self):
exp = Series([pd.NaT], index=["foo"])
tm.assert_series_equal(res, exp)

def test_min_max_dt64_with_NaT_precision(self):
# GH#60646 Make sure the reduction doesn't cast input timestamps to
# float and lose precision.
df = DataFrame(
{"foo": [pd.NaT, pd.NaT, Timestamp("2012-05-01 09:20:00.123456789")]},
dtype="datetime64[ns]",
)

res = df.min(axis=1)
exp = df.foo.rename(None)
tm.assert_series_equal(res, exp)

res = df.max(axis=1)
exp = df.foo.rename(None)
tm.assert_series_equal(res, exp)

def test_min_max_td64_with_NaT_precision(self):
# GH#60646 Make sure the reduction doesn't cast input timedeltas to
# float and lose precision.
df = DataFrame(
{
"foo": [
pd.NaT,
pd.NaT,
to_timedelta("10000 days 06:05:01.123456789"),
],
},
dtype="timedelta64[ns]",
)

res = df.min(axis=1)
exp = df.foo.rename(None)
tm.assert_series_equal(res, exp)

res = df.max(axis=1)
exp = df.foo.rename(None)
tm.assert_series_equal(res, exp)

def test_min_max_dt64_with_NaT_skipna_false(self, request, tz_naive_fixture):
# GH#36907
tz = tz_naive_fixture
Expand Down
Loading