我正在尝试对数据重新采样以获取总和。此重采样仅需基于时间。我想将时间分为6个小时,所以无论日期如何,我都会得到4笔款项。
我的df看起来像这样:
booking_count
date_time
2013-04-04 08:32:25 58
2013-04-04 18:43:11 1
2013-30-04 12:39:15 52
2013-14-05 06:51:33 99
2013-01-06 23:59:17 1
2013-03-06 19:37:25 42
2013-27-06 04:12:01 38
使用此示例数据,我希望得到以下结果:
00:00:00 38
06:00:00 157
12:00:00 52
18:00:00 43
为了解决日期问题,我尝试仅保留时间值:
df['time'] = pd.DatetimeIndex(df['date_time']).time
new_df = df[['time', 'booking_bool']].set_index('time').resample('360min').sum()
不幸的是,这没有用。如何获得所需的结果? resample()
甚至适合此任务吗?
答案 0 :(得分:4)
我不认为resample()
是执行此操作的好方法,因为您需要根据小时独立于一天进行分组。也许您可以尝试使用cut
和自定义bins
参数,然后再使用通常的groupby
bins = np.arange(start=0, stop=24+6, step=6)
group = df.groupby(pd.cut(
df.index.hour,
bins, right=False,
labels=pd.date_range('00:00:00', '18:00:00', freq='6H').time)
).sum()
group
# booking_count
# 00:00:00 38
# 06:00:00 157
# 12:00:00 52
# 18:00:00 44