wolfram-mathematica - 如何在 Mathematica 中更快地选择子列表?

标签 wolfram-mathematica

我的问题听起来比较笼统,但我有一个具体的例子。我有一个表单中的数据列表:

plotDataAll={{DateList1, integerValue1}, {DateList2, integerValue2}...}

日期按时间顺序排序,即 plotDataAll[[2,1]]plotDataAll[[1,1]] 更新。

我想创建特定时期(24 小时前、1 周前等)的绘图。为此,我只需要一部分数据。以下是我如何得到我想要的:

mostRecentDate=Max[Map[AbsoluteTime, plotDataAll[[All,1]]]];
plotDataLast24h=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-86400.)&];
plotDataLastWeek=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-604800.)&];
plotDataLastMonth=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-2.592*^6)&];
plotDataLast6M=Select[plotDataAll,AbsoluteTime[#[[1]]]>(mostRecentDate-1.5552*^7)&];

然后我使用 DateListPlot 来绘制数据。如果您需要对许多数据集执行此操作,这会变得很慢。
我想到的是,如果我能找到列表中满足日期条件的第一个元素的索引,因为它是按时间顺序排序的,那么其余的元素也应该满足条件。所以我会:

plotDataLast24h=plotDataAll[[beginningIndexThatSatisfiesLast24h;;Length[plotDataAll]]

但是如何获取第一个满足条件的元素的索引呢?

如果您有更快的方法,请分享您的答案。另外,如果您有一个简单、更快但次优的解决方案,那也没关系。

编辑:
时间数据的间隔不固定。

最佳答案

如果您的数据是定期的,您应该能够知道有多少个元素构成一天、一周等,并使用 Part

plotDataAll2[[knownIndex;;-1]]

或者更具体地说,如果数据是每小时的:

plotDataAll2[[-25;;-1]]

将为您提供最近 24 小时的信息。如果间距不规则,则使用SelectPick。不幸的是,Mma 中的日期和时间函数非常慢。如果您要进行大量日期和时间计算,最好只转换一次 AbsoluteTime ,然后使用它。您还会注意到,如果使用 AbsoluteTimeDateListPlot 的渲染速度会更快。

plotDataAll2=plotDataAll;
plotDataAll2[[All,1]]=AbsoluteTime/@plotDataAll2[[All,1]];
mostRecentDate=plotDataAll2[[-1,1]]

在我的计算机上 Pick 速度大约快 3 倍,但您还可以对以下代码进行其他改进:

selectInterval[data_, interval_] := (tmp = data[[-1, 1]] - interval; 
  Select[data, #[[1]] > tmp &])

pickInterval[data_, interval_] := (tmp = data[[-1, 1]] - interval; 
  Pick[data, Sign[data[[All, 1]] - tmp], 1])

因此要查找上周内的数据:

Timing[selectInterval[plotDataAll2, 604800]]
Timing[pickInterval[plotDataAll2, 604800]]

关于wolfram-mathematica - 如何在 Mathematica 中更快地选择子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8949177/

相关文章:

wolfram-mathematica - 这是 Mathematica 8 的错误吗?

graphics - 使用 Mathematica 中的图形在对象内均匀分布点

wolfram-mathematica - 如何使 PlotLegend 与 Mathematica 中的 ParametricPlot 一起使用?

wolfram-mathematica - 在mathematica中保持Graphics3D的绘图区域一致

string - 如何根据 Mathematica 中的部分字符串匹配进行选择

wolfram-mathematica - Mathematica 中清除和删除的区别

vector - Mathematica 如何绘制具有 1 个变量的矢量场?

wolfram-mathematica - 在更高的抽象级别上进行概率计算

python - python中的StopIteration错误

arrays - 包含结构数组的 MAT 文件的导入 [] - 仅导入第一个元素?