使用 Pandas 在时间序列数据中查找缺失的分钟数据

Sak*_*ssi 2 python numpy pandas

我有一个时间序列数据,每分钟都有数据,但由于传感器的一些问题,有时没有获取数据,也没有记录该分钟数据。我想知道这发生在哪一天和哪一个小时。我有熊猫数据框中的数据。这是我要存储在数据框中的代码片段,我想显示未收到哪些分钟数据。

l=['Year', 'Month', 'Day', 'Hour', 'Minute']
df = pd.DataFrame(columns=l)
k=0

if __name__ == '__main__':
    client = MongoClient("localhost", 27017, maxPoolSize=50)
    db=client.test
    collection=db['data']
    cursor = collection.find({"deviceId":3},{"timestamp":1,"cd":1}).sort("timestamp",-1).limit(1000)
    for document in cursor:
        for key,value in document.items()[1:-1]:
            df.loc[k,'Year']=2017
            df.loc[k,'Month']=value.month
            df.loc[k,'Day']=value.day
            df.loc[k,'Hour']=value.hour
            df.loc[k,'Minute']=value.minute
            k=k+1
    minute_a = pd.Series(np.arange(0, 60))
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用isin函数 usingminute_a但由于每个小时我都必须检查,我不知道该怎么做?

小智 5

isin将是这样做的好方法。但是,执行此操作的最简单方法是将您的传感器时间数据展平为一个,DatetimeIndex以便您可以将其与参考DatetimeIndex.

# creating reference DatetimeIndex idx_ref with a minute frequency
end=datetime.now().replace(second=0, microsecond=0)
dt = end - timedelta(days=1)
idx_ref = pd.DatetimeIndex(start=dt, end=end,freq='min')

# idx_dat represents your DatetimeIndex from the sensor
gaps = idx_ref[~idx_ref.isin(idx_dat)]
Run Code Online (Sandbox Code Playgroud)

当然,假设您只对时间间隔感兴趣。