从d查找缺失的时间间隔

2024-05-01 21:55:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在CSV文件中有一个日期列表,我想在一天中的一个小时时间段中查找并添加缺失的时间间隔。

数据如下:

id  city     reading date 
33  US-Ohio  06/18/2011 23:00:00  
33  US-Ohio  06/19/2011 00:00:00  
33  US-Ohio  06/19/2011 01:00:00  
33  US-Ohio  06/19/2011 02:00:00  
33  US-Ohio  06/19/2011 06:00:00  
33  US-Ohio  06/19/2011 07:00:00  
33  US-Ohio  06/19/2011 08:00:00  
34  US-NYC   06/19/2011 06:00:00  
34  US-NYC   06/19/2011 08:00:00

因此,需要插入的缺失数据是

^{pr2}$

我已经使用pandas将其转换为datetime,代码如下:

games['reading_date'] =  pd.to_datetime(games['reading_date'], format='%m/%d/%y %H:%M')

日期是重复的,所以设置一个索引和重新采样是行不通的,因为不同城市的缺失时间不同,而且索引会重复多次 我只需要添加这些缺失的每小时间隔,并保持所有其他列为空。如何在python中执行此操作?


Tags: 文件csv数据列表datetimedate间隔时间
1条回答
网友
1楼 · 发布于 2024-05-01 21:55:59

更新数据集的更新答案:

按id&city分组并应用asfreq函数。在

df.groupby(['id', 'city'], as_index=False).apply(lambda x: x.set_index('reading date').asfreq('1H').reset_index())

# outputs:

                         id      city
  reading date
0 2011-06-18 23:00:00  33.0   US-Ohio
  2011-06-19 00:00:00  33.0   US-Ohio
  2011-06-19 01:00:00  33.0   US-Ohio
  2011-06-19 02:00:00  33.0   US-Ohio
  2011-06-19 03:00:00   NaN       NaN
  2011-06-19 04:00:00   NaN       NaN
  2011-06-19 05:00:00   NaN       NaN
  2011-06-19 06:00:00  33.0   US-Ohio
  2011-06-19 07:00:00  33.0   US-Ohio
  2011-06-19 08:00:00  33.0   US-Ohio
1 2011-06-19 06:00:00  34.0    US-NYC
  2011-06-19 07:00:00   NaN       NaN
  2011-06-19 08:00:00  34.0    US-NYC

编辑:原始答案

确保Column 1是日期时间。在

然后,将index设置为“Column 1”并使用pandas.DataFrame.asFreq在

^{pr2}$

相关问题 更多 >