假设我为一天定义了 4 个自定义时间段:早上 6 点到中午 12 点、中午 12 点到晚上 7 点、晚上 7 点到凌晨 00 点、早上 00 点到早上 6 点。 pandas 中将给定时间戳转换为这些期间之一的简洁方法是什么?
最佳答案
也许你可以使用numpy.searchsorted
:
>>> idx
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-08-26 22:20:34.580486, ..., 2014-08-29 05:20:34.581053]
Length: 12, Freq: None, Timezone: None
>>> idx.hour
array([22, 3, 8, 13, 18, 23, 4, 9, 14, 19, 0, 5], dtype=int32)
>>> p = np.array(['00am-06am', '06am-12pm', '12pm-07pm', '07pm-00am'])
>>> p[np.searchsorted([6, 12, 19, 24], idx.hour)]
array(['07pm-00am', '00am-06am', '06am-12pm', '12pm-07pm', '12pm-07pm',
'07pm-00am', '00am-06am', '06am-12pm', '12pm-07pm', '12pm-07pm',
'00am-06am', '00am-06am'],
dtype='<U9')
关于python - 将时间戳转换为 Pandas 中的自定义周期之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517830/