【发布时间】:2021-07-23 17:55:02
【问题描述】:
我有一个气象时间序列df:
df = pd.DataFrame({'date':['11/10/2017 0:00','11/10/2017 03:00','11/10/2017 06:00','11/10/2017 09:00','11/10/2017 12:00',
'11/11/2017 0:00','11/11/2017 03:00','11/11/2017 06:00','11/11/2017 09:00','11/11/2017 12:00',
'11/12/2017 00:00','11/12/2017 03:00','11/12/2017 06:00','11/12/2017 09:00','11/12/2017 12:00'],
'value':[850,np.nan,np.nan,np.nan,np.nan,500,650,780,np.nan,800,350,690,780,np.nan,np.nan]})
df['date'] = pd.to_datetime(df.date.astype(str), format='%m/%d/%Y %H:%M',errors ='coerce')
df.index = pd.DatetimeIndex(df.date)
通过这个数据框,我试图找出事件的开始时间和结束时间:
(df["value"] < 1000)
我使用了类似于How to find the start time and end time of an event in python?的解决方案 修改后的代码:
current_event = None
result = []
for event, time in zip((df["value"] < 1000), df.index):
if event != current_event:
if current_event is not None:
result.append([current_event, start_time, time - pd.DateOffset(hours = 1, minutes = 30)])
current_event, start_time = event, time - pd.DateOffset(hours = 1, minutes = 30)
df = pd.DataFrame(result, columns=['Event','StartTime','EndTime'])
df
输出是:
Event StartTime EndTime
0 True 2017-11-09 22:30:00 2017-11-10 01:30:00
1 False 2017-11-10 01:30:00 2017-11-10 22:30:00
2 True 2017-11-10 22:30:00 2017-11-11 07:30:00
3 False 2017-11-11 07:30:00 2017-11-11 10:30:00
4 True 2017-11-11 10:30:00 2017-11-12 07:30:00
所需的输出与上面的输出不同:
-
第二行(索引 1)中的
EndTime 为 2017-11-10 13:30:00
-
EndTime 第五行(索引 4 )为 2017-11-11 13:30:00
-
新行第六行(索引 5)和第 6 行
逻辑:
-
由于时间戳相隔 3 小时,因此假设事件在时间戳前 1 小时 30 分钟开始,在时间戳后 1 小时 30 分钟结束。
-
如果两个连续事件相似,则它们加起来如下:第一个时间戳之前的 1 小时 30 分钟到第二个时间戳之后的 1 小时 30 分钟,依此类推。
-
一天中第一个事件的开始时间,即时间 00:00 应始终为 00:00 时间戳前 1 小时 30 分钟,即前一天的 22:30。
-
一天中最后一个事件的结束时间,即 12:00 应该始终是 12:00 时间戳之后 1 小时 30 分钟,即同一天的 13:30。
对于这个问题的任何及时帮助将不胜感激。试图拼命修复它,但还没有成功。
非常感谢!
【问题讨论】:
-
你确定你已经分享了你最新的代码吗?因为我在
time - pd.DateOffset(hours = 1, minutes = 30)的第一个实例周围得到TypeError: unsupported operand type(s) for -: 'int' and 'datetime.timedelta' -
代码是最新的。首先,您需要将索引转换为 datetimeindex,如下所示: df['date'] = pd.to_datetime(df.date.astype(str), format='%m/%d/%Y %H:%M', errors ='coerce') df.index = pd.DatetimeIndex(df.date) df.drop('date', axis = 1, inplace = True)
-
酷,继续把代码编辑到你的原始代码块中,我会尝试再次运行它
-
@Kevin ,原代码块中已经编辑了代码..
标签: python pandas dataframe time-series python-datetime