假设我为一天定义了4个自定义时间段:6 am-12pm,12 pm-7pm,7 pm-00am,00 am-6am。
在熊猫中,将给定时间戳转换为其中一个周期的干净方法是什么?
最佳答案
也许您可以使用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')