繁体   English   中英

采样numpy数组的最快方法是什么?

[英]What is the fastest way to sample slices of numpy arrays?

我有一个3D(时间,X,Y)numpy数组,包含6个小时的时间序列几年。 (比如5)。 我想创建一个采样时间序列,其中包含从可用记录中随机抽取的每个日历日的1个实例(每天5种可能性),如下所示。

  • 1月01日:2006年
  • 1月02日:2011年
  • 1月03日:2009年
  • ...

这意味着我需要从01/01/2006获取4个值,从2011年2月1日起获取4个值等。我有一个工作版本,其工作方式如下:

  • 重塑输入数组以添加“年”维度(时间,年份,X,Y)
  • 创建一个随机生成的0到4之间整数的365值数组
  • 使用np.repeat和整数数组仅提取相关值:

例:

sampledValues = Variable[np.arange(numberOfDays * ValuesPerDays), sampledYears.repeat(ValuesPerDays),:,:]

这似乎有效,但我想知道这是否是解决我问题的最佳/最快方法? 速度很重要,因为我在循环中这样做,adn将受益于测试尽可能多的情况。

我这样做了吗?

谢谢

编辑我忘了提到我过滤了输入数据集以删除闰年的第29个。

基本上,该操作的目的是找到一个365天的样本,与平均值等方面的长期时间序列匹配良好。如果采样的时间序列通过我的质量测试,我想导出它并重新开始。

2008年是366天,所以不要重塑。

看看scikits.timeseries

import scikits.timeseries as ts

start_date = ts.Date('H', '2006-01-01 00:00')
end_date = ts.Date('H', '2010-12-31 18:00')
arr3d = ... # your 3D array [time, X, Y]

dates = ts.date_array(start_date=start_date, end_date=end_date, freq='H')[::6]
t = ts.time_series(arr3d, dates=dates)
# just make sure arr3d.shape[0] == len(dates) !

现在,您可以使用日/月/年对象访问t数据:

t[np.logical_and(t.day == 1, t.month == 1)]

例如:

for day_of_year in xrange(1, 366):
    year = np.random.randint(2006, 2011)

    t[np.logical_and(t.day_of_year == day_of_year, t.year == year)]
    # returns a [4, X, Y] array with data from that day

使用t的属性来使其与闰年一起工作。

我不认为真正需要重塑数组,因为您可以在采样过程中嵌入年份信息,并使数组保持原始形状。

例如,您可以生成随机偏移(从0到365),并选择具有索引的切片,例如, n*365 + offset

无论如何,我不认为你的问题是完整的,因为我不太明白你需要做什么,或为什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM