Skip to content

BUG: Add frequency to DatetimeArray/TimedeltaArray take #58382

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

Merged
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 @@ -556,6 +556,7 @@ MultiIndex
- :func:`DataFrame.loc` with ``axis=0`` and :class:`MultiIndex` when setting a value adds extra columns (:issue:`58116`)
- :meth:`DataFrame.melt` would not accept multiple names in ``var_name`` when the columns were a :class:`MultiIndex` (:issue:`58033`)
- :meth:`MultiIndex.insert` would not insert NA value correctly at unified location of index -1 (:issue:`59003`)
- :func:`MultiIndex.get_level_values` accessing a :class:`DatetimeIndex` does not carry the frequency attribute along (:issue:`58327`, :issue:`57949`)
-

I/O
Expand Down
22 changes: 22 additions & 0 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,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(
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)
result._freq = freq

return result

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

Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexes/multi/test_get_level_values.py
Original file line number Diff line number Diff line change
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
Loading