【发布时间】:2019-12-30 17:48:02
【问题描述】:
在我最初的问题here 给出了非常有建设性的答案之后,我想为我的原始数据框定制它。
我需要进行更改的数据框来自:nightframe=new_df.between_time('22:00','04:00'),前几行如下所示:
date time diffs criteria 1
datetime
2018-01-05 22:00:00 2018-01-05 22:00:00 0.0 True
2018-01-05 23:00:00 2018-01-05 23:00:00 -1.0 False
2018-01-06 00:00:00 2018-01-06 00:00:00 1.0 True
2018-01-06 01:00:00 2018-01-06 01:00:00 -2.0 False
2018-01-06 02:00:00 2018-01-06 02:00:00 -1.0 True
2018-01-06 03:00:00 2018-01-06 03:00:00 1.0 True
2018-01-06 04:00:00 2018-01-06 04:00:00 1.0 False
2018-01-06 22:00:00 2018-01-06 22:00:00 -1.0 True
如果时间是从 00:00 到 04:00,我需要将日期分配给前一个日期。我已经根据我的情况尝试了这些代码,但它们不起作用:
condition = nightframe['time'].isin([0,1,2,3,4])
condition = nightframe['time'].dt.time.isin(\
['00:00','01:00','02:00','03:00','04:00'])
condition = nightframe['time'](['00:00','01:00','02:00','03:00','04:00'])
如果条件有效,我想我需要的数据框可以来自:nightframe['date']=np.where(condition, nightframe['date']-pd.Timedelta('1 day'), nightframe['date']),并且应该给出这个视图:
date time diffs criteria 1
datetime
2018-01-05 22:00:00 2018-01-05 22:00:00 0.0 True
2018-01-05 23:00:00 2018-01-05 23:00:00 -1.0 False
2018-01-06 00:00:00 2018-01-05 00:00:00 1.0 True
2018-01-06 01:00:00 2018-01-05 01:00:00 -2.0 False
2018-01-06 02:00:00 2018-01-05 02:00:00 -1.0 True
2018-01-06 03:00:00 2018-01-05 03:00:00 1.0 True
2018-01-06 04:00:00 2018-01-05 04:00:00 1.0 False
2018-01-06 22:00:00 2018-01-06 22:00:00 -1.0 True
2018-01-06 23:00:00 2018-01-06 23:00:00 1.0 True
2018-01-07 00:00:00 2018-01-06 00:00:00 0.0 False
2018-01-07 01:00:00 2018-01-06 01:00:00 1.0 True
2018-01-07 02:00:00 2018-01-06 02:00:00 0.0 False
2018-01-07 03:00:00 2018-01-06 03:00:00 -1.0 False
2018-01-07 04:00:00 2018-01-06 04:00:00 1.0 True
2018-01-07 22:00:00 2018-01-07 22:00:00 1.0 True
注意:'datetime' 是我的数据框的索引,而 nightframe 列的类型是:
print(nightframe.dtypes)
date object
time object
diffs float64
criteria 1 object
dtype: object
print(nightframe.index.dtype)
datetime64[ns]
【问题讨论】:
-
请多解释一下你的逻辑。在这种情况下,
diffs和criteria列的功能是什么? dod2018-01-07突然从哪里来的?您的预期输出是否基于您给定的示例数据框? -
diffs和criteria列不考虑,而dates来自datetime索引列。我要做的是将00:00到04:00的时间分配给前一个日期,而日期时间索引将保持不变。
标签: python-3.x pandas datetime timedelta