可能需要使用内插和重采样,将时间序列数据的数据集从不规则时间间隔的一个数据集转换为规则时间序列。
Python的 pandas.Dataframe.resample
是可以执行此操作的函数。 Javascript可以做同样的事情吗?时间序列数据集存储在Mongodb中。
最佳答案
这是可能的。请记住,Pandas是专门为此类任务而构建的库,也是它的野兽,而MongoDB则是一个数据库。但是,如果人们忽略了使用插值的可能需求,则很可能满足您的需求:
假设您将以下数据存储在名为devices
的MongoDB集合中
/* 0 */
{
"_id" : ObjectId("543fc08ccf1e8c06c0288802"),
"t" : ISODate("2014-10-20T14:56:44.097+02:00"),
"a" : "192.168.0.16",
"i" : 0,
"o" : 32
}
/* 1 */
{
"_id" : ObjectId("543fc08ccf1e8c06c0288803"),
"t" : ISODate("2014-10-20T14:56:59.107+02:00"),
"a" : "192.168.0.16",
"i" : 14243,
"o" : 8430
}
and so on...
在这种情况下,大约每15秒采样一次,但也可能是不规则的。如果要在某天将其重新采样到5分钟的边界,则应执行以下操作:
var low = ISODate("2014-10-23T00:00:00.000+02:00")
var high = ISODate("2014-10-24T00:00:00.000+02:00")
var interval = 5*60*1000;
db.devices.aggregate([
{$match: {t:{$gte: low, $lt: high}, a:"192.168.0.16"}},
{$group: {
_id:{
$subtract: ["$t", {
$mod: [{
$subtract: ["$t", low]
}, interval]
}]
},
total: {$sum: 1},
incoming: {$sum: "$i"},
outgoing: {$sum: "$o"},
}
},
{
$project: {
total: true,
incoming: true,
outgoing: true,
incoming_avg: {$divide: ["$incoming", "$total"]},
outgoing_avg: {$divide: ["$outgoing", "$total"]},
},
},
{$sort: {_id : 1}}
])
这将导致这样的事情
{
"result" : [
{
"_id" : ISODate("2014-10-23T07:25:00.000+02:00"),
"total" : 8,
"incoming" : 11039108,
"outgoing" : 404983,
"incoming_avg" : 1379888.5,
"outgoing_avg" : 50622.875
},
{
"_id" : ISODate("2014-10-23T07:30:00.000+02:00"),
"total" : 19,
"incoming" : 187241,
"outgoing" : 239912,
"incoming_avg" : 9854.78947368421,
"outgoing_avg" : 12626.94736842105
},
{
"_id" : ISODate("2014-10-23T07:35:00.000+02:00"),
"total" : 17,
"incoming" : 22420099,
"outgoing" : 1018766,
"incoming_avg" : 1318829.352941176,
"outgoing_avg" : 59927.41176470588
},
...
如果要丢弃总输入,则只需在$ project阶段中删除该行即可。如果您存储的数据类似于rrdtool命名的仪表(温度,cpu,传感器数据),incoming_average只是如何计算平均值的一个示例。如果您只是在那个时间间隔内汇总的总和(即传入和传出字段)之后,则可以将整个$ project阶段排除在外。它仅用于计算时间间隔的平均值。
参见Mongo aggregation of ISODate into 45 minute chunks