Skip to content

Commit 671554d

Browse files
added fix for column index for DatetimeIndex type
1 parent ee0902a commit 671554d

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

pandas/core/generic.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4002,6 +4002,13 @@ class max_speed
40024002
indices = np.asarray(indices, dtype=np.intp)
40034003
if axis == 0 and indices.ndim == 1 and is_range_indexer(indices, len(self)):
40044004
return self.copy(deep=False)
4005+
4006+
4007+
if axis == 1 and indices.ndim == 1 and is_range_indexer(indices, len(self.columns)):
4008+
# check if index is of type period, sets to object for slicing correct columns
4009+
if isinstance(self.index, DatetimeIndex) or isinstance(self.index, PeriodIndex):
4010+
return self.copy(deep=False).astype('object')
4011+
return self.copy(deep=False)
40054012

40064013
new_data = self._mgr.take(
40074014
indices,

pandas/tests/series/indexing/test_getitem.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
Categorical,
2525
DataFrame,
2626
DatetimeIndex,
27+
PeriodIndex,
2728
Index,
2829
Series,
2930
Timestamp,
@@ -411,7 +412,33 @@ def test_getitem_uint_array_key(self, any_unsigned_int_numpy_dtype):
411412
ser[key]
412413
with pytest.raises(KeyError, match="4"):
413414
ser.loc[key]
414-
415+
416+
417+
def test_pivot_periodindex_hourly(self):
418+
#GH issue 60273
419+
pr = period_range('2024-01-01 00:00:00', '2024-01-01 02:00:00', freq='h')
420+
df = DataFrame(index=pr)
421+
df['date'] = df.index.to_timestamp().floor('D')
422+
df['hour'] = df.index.hour
423+
df.index.name = 'value'
424+
df = df.reset_index()
425+
df = df.pivot(index='date', columns='hour', values='value')
426+
df=df.astype('object')
427+
result = df[[0, 1, 2]]
428+
expected = df
429+
430+
tm.assert_frame_equal(result, expected)
431+
432+
def test_getitem_periodindex_daily(self):
433+
# GH issue 60273
434+
df = pd.DataFrame(
435+
data=[
436+
pd.Period("2024-01-01", freq="D"),
437+
pd.Period("2024-01-02", freq="D"),
438+
pd.Period("2024-01-03", freq="D"),
439+
]
440+
).T
441+
tm.assert_frame_equal(df[[0, 1, 2]], df)
415442

416443
class TestGetitemBooleanMask:
417444
def test_getitem_boolean(self, string_series):

0 commit comments

Comments
 (0)