Skip to content

Commit 74ad212

Browse files
committed
preserving freq without patching
1 parent a946317 commit 74ad212

File tree

1 file changed

+29
-30
lines changed

1 file changed

+29
-30
lines changed

pandas/core/algorithms.py

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,26 @@ def value_counts_internal(
867867
Series,
868868
)
869869

870+
def _preserve_freq(original_values, result_index):
871+
freq = getattr(original_values, "freq", None)
872+
873+
if (
874+
freq is not None
875+
and type(original_values) is type(result_index)
876+
and len(result_index) == len(original_values)
877+
and result_index.equals(original_values)
878+
):
879+
try:
880+
# Rebuild index with freq using the same constructor
881+
return type(result_index)(
882+
result_index._data, freq=freq, name=result_index.name
883+
)
884+
except (TypeError, ValueError):
885+
# If reconstruction fails, return original index
886+
pass
887+
888+
return result_index
889+
870890
index_name = getattr(values, "name", None)
871891
name = "proportion" if normalize else "count"
872892

@@ -929,6 +949,15 @@ def value_counts_internal(
929949
# Starting in 3.0, we no longer perform dtype inference on the
930950
# Index object we construct here, xref GH#56161
931951
idx = Index(keys, dtype=keys.dtype, name=index_name)
952+
953+
if (
954+
bins is None
955+
and not sort
956+
and hasattr(values, "freq")
957+
and values.freq is not None
958+
):
959+
idx = _preserve_freq(values, idx)
960+
932961
result = Series(counts, index=idx, name=name, copy=False)
933962

934963
if sort:
@@ -937,36 +966,6 @@ def value_counts_internal(
937966
if normalize:
938967
result = result / counts.sum()
939968

940-
# freq patching for DatetimeIndex, TimedeltaIndex
941-
try:
942-
from pandas import (
943-
DatetimeIndex,
944-
TimedeltaIndex,
945-
)
946-
947-
if (
948-
bins is None
949-
and not sort
950-
and isinstance(values, (DatetimeIndex, TimedeltaIndex))
951-
and values.freq is not None
952-
and isinstance(result.index, (DatetimeIndex, TimedeltaIndex))
953-
and len(result.index) == len(values)
954-
and result.index.equals(values)
955-
):
956-
base_freq = values.freq
957-
# Rebuild the index with the original freq; name preserved.
958-
if isinstance(result.index, DatetimeIndex):
959-
result.index = DatetimeIndex(
960-
result.index._data, freq=base_freq, name=result.index.name
961-
)
962-
else: # TimedeltaIndex
963-
result.index = TimedeltaIndex(
964-
result.index._data, freq=base_freq, name=result.index.name
965-
)
966-
except Exception:
967-
# If freq patching fails, does not affect value_counts
968-
pass
969-
970969
return result
971970

972971

0 commit comments

Comments
 (0)