Skip to content
Open
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 @@ -976,6 +976,7 @@ Datetimelike
- Bug in comparison between objects with pyarrow date dtype and ``timestamp[pyarrow]`` or ``np.datetime64`` dtype failing to consider these as non-comparable (:issue:`62157`)
- Bug in constructing arrays with :class:`ArrowDtype` with ``timestamp`` type incorrectly allowing ``Decimal("NaN")`` (:issue:`61773`)
- Bug in constructing arrays with a timezone-aware :class:`ArrowDtype` from timezone-naive datetime objects incorrectly treating those as UTC times instead of wall times like :class:`DatetimeTZDtype` (:issue:`61775`)
- Bug in retaining frequency in :meth:`value_counts` specifically for :meth:`DatetimeIndex` and :meth:`TimedeltaIndex` (:issue:`33830`)
- Bug in setting scalar values with mismatched resolution into arrays with non-nanosecond ``datetime64``, ``timedelta64`` or :class:`DatetimeTZDtype` incorrectly truncating those scalars (:issue:`56410`)


Expand Down
15 changes: 15 additions & 0 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,8 +868,10 @@ def value_counts_internal(
dropna: bool = True,
) -> Series:
from pandas import (
DatetimeIndex,
Index,
Series,
TimedeltaIndex,
)

index_name = getattr(values, "name", None)
Expand Down Expand Up @@ -934,6 +936,19 @@ def value_counts_internal(
# Starting in 3.0, we no longer perform dtype inference on the
# Index object we construct here, xref GH#56161
idx = Index(keys, dtype=keys.dtype, name=index_name)

if (
bins is None
and not sort
and isinstance(values, (DatetimeIndex, TimedeltaIndex))
and values.inferred_freq is not None
and len(idx) == len(values)
and idx.equals(values)
):
# freq preservation
# Rebuild idx with the correct type and inferred frequency
idx.freq = values.inferred_freq
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
idx.freq = values.inferred_freq
idx.freq = values.inferred_freq # type: ignore[attr-defined]


result = Series(counts, index=idx, name=name, copy=False)

if sort:
Expand Down
78 changes: 78 additions & 0 deletions pandas/tests/base/test_value_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,81 @@ def test_value_counts_object_inference_deprecated():
exp = dti.value_counts()
exp.index = exp.index.astype(object)
tm.assert_series_equal(res, exp)


@pytest.mark.parametrize(
"index",
[
pd.date_range("2016-01-01", periods=5, freq="D"),
pd.timedelta_range(Timedelta(0), periods=5, freq="h"),
],
ids=["DatetimeIndex[D]", "TimedeltaIndex[h]"],
)
@pytest.mark.parametrize(
"build,kwargs,exp_preserve,exp_hasnans,exp_index_fn",
[
(lambda idx: idx, {"sort": False}, True, False, lambda idx, obj: idx),
(
lambda idx: idx,
{"sort": False, "normalize": True},
True,
False,
lambda idx, obj: idx,
),
(lambda idx: idx, {}, False, False, None),
(
lambda idx: idx.insert(1, idx[1]),
{"sort": False},
False,
False,
lambda idx, obj: type(idx)(idx, freq=None),
),
(
lambda idx: idx.delete(2),
{"sort": False},
False,
False,
lambda idx, obj: type(idx)(obj, freq=None),
),
(
lambda idx: idx.insert(1, pd.NaT),
{"sort": False, "dropna": False},
False,
True,
lambda idx, obj: type(idx)(
list(idx[:1]) + [pd.NaT] + list(idx[1:]), freq=None
),
),
(
lambda idx: idx.insert(1, pd.NaT),
{"sort": False, "dropna": True},
False,
False,
lambda idx, obj: type(idx)(idx, freq=None),
),
],
)
def test_value_counts_freq_datetimelike(
index, build, kwargs, exp_preserve, exp_hasnans, exp_index_fn
):
obj = build(index)
vc = obj.value_counts(**kwargs)

# without sort
if exp_index_fn is not None:
expected_idx = exp_index_fn(index, obj)
tm.assert_index_equal(vc.index, expected_idx)

# freq preservation / drop
if exp_preserve:
assert vc.index.freq == index.freq
else:
assert vc.index.freq is None

# NaT presence
assert vc.index.hasnans is exp_hasnans

# without normalize
if kwargs.get("normalize", False):
expected_val = 1.0 / len(index)
assert np.isclose(vc.to_numpy(), expected_val).all()
Loading