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: Add frequency to DatetimeArray/TimedeltaArray take #58382

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Expand Up @@ -440,6 +440,7 @@ Missing
MultiIndex
^^^^^^^^^^
- :func:`DataFrame.loc` with ``axis=0`` and :class:`MultiIndex` when setting a value adds extra columns (:issue:`58116`)
- :func:`MultiIndex.get_level_values` accessing a :class:`DatetimeIndex` does not carry the frequency attribute along (:issue:`58327`, :issue:`57949`)
- :meth:`DataFrame.melt` would not accept multiple names in ``var_name`` when the columns were a :class:`MultiIndex` (:issue:`58033`)
-

Expand Down
22 changes: 22 additions & 0 deletions pandas/core/arrays/datetimelike.py
Expand Up @@ -66,6 +66,7 @@
ScalarIndexer,
Self,
SequenceIndexer,
TakeIndexer,
TimeAmbiguous,
TimeNonexistent,
npt,
Expand Down Expand Up @@ -2340,6 +2341,27 @@ def interpolate(
return self
return type(self)._simple_new(out_data, dtype=self.dtype)

def take(
annika-rudolph marked this conversation as resolved.
Show resolved Hide resolved
self,
indices: TakeIndexer,
*,
allow_fill: bool = False,
fill_value: Any = None,
axis: AxisInt = 0,
) -> Self:
result = super().take(
indices=indices, allow_fill=allow_fill, fill_value=fill_value, axis=axis
)

indices = np.asarray(indices, dtype=np.intp)
maybe_slice = lib.maybe_indices_to_slice(indices, len(self))

if isinstance(maybe_slice, slice):
freq = self._get_getitem_freq(maybe_slice)
annika-rudolph marked this conversation as resolved.
Show resolved Hide resolved
result._freq = freq

return result

# --------------------------------------------------------------
# Unsorted

Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexes/multi/test_get_level_values.py
Expand Up @@ -122,3 +122,12 @@ def test_values_loses_freq_of_underlying_index():
midx.values
assert idx.freq is not None
tm.assert_index_equal(idx, expected)


def test_get_level_values_gets_frequency_correctly():
# GH#57949 GH#58327
datetime_index = date_range(start=pd.to_datetime("1/1/2018"), periods=4, freq="YS")
other_index = ["A"]
multi_index = MultiIndex.from_product([datetime_index, other_index])

assert multi_index.get_level_values(0).freq == datetime_index.freq