首页 > 解决方案 > 如何在python中用0填充分钟时间序列数据?

问题描述

我有一个如下的数据集“nodup”(未按时间排序)。它是原始数据的子集,未排序。我需要每 15 分钟获取一次记录,例如 08:15、08:30、08:45 ......但它只在 occupancy = 1 时保留记录。

我需要做的是让 occupancy=0,并通过前一个值和下一个值的平均值(来自同一设备)自动填充相关的新生成的 co2 和湿度。:

 device     occupancy                time         co2   humidity 
   1          1              2019-06-27 10:17:22    818     40
   2          1              2019-06-27 10:17:22    818     39
   3          1              2019-06-27 08:00:05    625     40
   4          1              2019-06-27 12:16:53    723     40
  ....
   1          1              2019-06-28 10:17:22    818     40
   2          1              2019-06-28 10:17:22    818     39
   3          1              2019-06-28 08:02:05    625     40
   4          1              2019-06-28 12:16:53    723     40
  ....

我想要的是作为示例(根据以前的数据生成 15 分钟的记录,按时间排序):

 device     occupancy                time         co2   humidity 
   1          1              2019-06-27 08:15     818     40
   2          0              2019-06-27 08:15     XXX     XX
   3          0              2019-06-27 08:15     XXX     XX
   4          1              2019-06-27 08:15     723     40
  ....
   1          1              2019-06-27 08:30     830     45
   2          0              2019-06-27 08:30     XXX     XX

我试过了

time_first =nodup['time'].min()  
time_last = nodup['time'].max() 

mux = pd.MultiIndex.from_product([pd.date_range(time_first, time_last,freq='15min'), 
nodup['device'].unique()], names=['time', 'device'])

result = nodup.set_index(['time','device']).reindex(mux, fill_value=0).reset_index()

但它运行到:

ValueError: cannot handle a non-unique multi-index!

任何人都可以在这方面提供帮助吗?当我查看原始数据时,该行中没有重复

标签: pythonarrayspandassorting

解决方案


我不知道你在问什么,但我会根据标题来回答

(例如,我不明白为什么 10:17 会变成 8:15)

nodup = pandas.DataFrame({
   'time': pandas.date_range('2019-01-03 22:12:13','2019-05-08 11:11:27',periods=1000)
})

使所有时间都有“:00”分钟

new_times = nodup['time'].dt.floor("1h")

推荐阅读