From 671554dc8110485a91a5816d8705b719ac2679f6 Mon Sep 17 00:00:00 2001 From: veronicabenedict Date: Sun, 8 Dec 2024 13:13:12 -0500 Subject: [PATCH] added fix for column index for DatetimeIndex type --- pandas/core/generic.py | 7 +++++ pandas/tests/series/indexing/test_getitem.py | 29 +++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 039bdf9c36ee7..f71755ce43bf0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4002,6 +4002,13 @@ class max_speed indices = np.asarray(indices, dtype=np.intp) if axis == 0 and indices.ndim == 1 and is_range_indexer(indices, len(self)): return self.copy(deep=False) + + + if axis == 1 and indices.ndim == 1 and is_range_indexer(indices, len(self.columns)): + # check if index is of type period, sets to object for slicing correct columns + if isinstance(self.index, DatetimeIndex) or isinstance(self.index, PeriodIndex): + return self.copy(deep=False).astype('object') + return self.copy(deep=False) new_data = self._mgr.take( indices, diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 8ba5e8452711d..400fbce5368a6 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -24,6 +24,7 @@ Categorical, DataFrame, DatetimeIndex, + PeriodIndex, Index, Series, Timestamp, @@ -411,7 +412,33 @@ def test_getitem_uint_array_key(self, any_unsigned_int_numpy_dtype): ser[key] with pytest.raises(KeyError, match="4"): ser.loc[key] - + + + def test_pivot_periodindex_hourly(self): + #GH issue 60273 + pr = period_range('2024-01-01 00:00:00', '2024-01-01 02:00:00', freq='h') + df = DataFrame(index=pr) + df['date'] = df.index.to_timestamp().floor('D') + df['hour'] = df.index.hour + df.index.name = 'value' + df = df.reset_index() + df = df.pivot(index='date', columns='hour', values='value') + df=df.astype('object') + result = df[[0, 1, 2]] + expected = df + + tm.assert_frame_equal(result, expected) + + def test_getitem_periodindex_daily(self): + # GH issue 60273 + df = pd.DataFrame( + data=[ + pd.Period("2024-01-01", freq="D"), + pd.Period("2024-01-02", freq="D"), + pd.Period("2024-01-03", freq="D"), + ] + ).T + tm.assert_frame_equal(df[[0, 1, 2]], df) class TestGetitemBooleanMask: def test_getitem_boolean(self, string_series):