如何使用这 2 个输入数组基于范围创建 tiled/stacked 数组 - 但不循环?
How can I create a tiled/stacked array based on ranges using these 2 input arrays - but without looping?
我的基本问题是我需要使用 2 个整数数组,并得到一个组合数组,它是使用 2 个初始数组的成对组合制成的许多范围的组合。
略有不同地说,我想使用2个数组,将它们组合起来产生一组范围,然后将这些范围合并在一起。重要的是,我需要在不使用任何循环的情况下执行此操作,因为我将需要执行将近 400 万次。
我的 2 个起始数组是:
import numpy as np
sd = np.array([3,3,4,2,5,1]) # StartDate
ed = np.array([4,5,5,5,8,2]) # EndDate
成对地,它们看起来像这样,结合(sd[i] 和 ed[i]):
[(3, 4), (3, 5), (4, 5), (2, 5), (5, 8), (1, 2)] # Pairwise combinations of StartDate and EndDate
举例来说,我可以迭代这些对,创建范围,示例如下:
[In]: range1 = np.arange(3,4)
[Out]: array([3])
[In]: range2 = np.arange(3,5)
[Out]: array([3,4])
...依此类推,得出最终输出:
array([3, 3, 4, 4, 2, 3, 4, 5, 6, 7, 1]) # End result where the arrays are tiled after one another
#(note first 3 digits are array 1 and array 2 from immediately above.
我的问题是我需要在不循环的情况下从输入数组转到输出数组,因为我已经尝试过这个版本,而且速度太慢了。非常感谢任何帮助。
你很幸运。这是一个单行解决方案:
indexer = np.r_[tuple([np.s_[i:j] for (i,j) in zip(sd,ed)])]
输出:
[3 3 4 4 2 3 4 5 6 7 1]
: "它是这样工作的:
np.s_[i:j] 创建一个从 start=i 到 end=j 的索引的切片对象(只是一个范围)。
np.r_[i:j, k:m] 创建切片 (i,j) 和 (k,m) 中的所有索引列表(您可以将更多切片传递给 np.r_ 将它们一次连接在一起。这是仅连接两个切片的示例。)
因此,索引器通过连接切片列表(每个切片是一个索引范围)来创建所有索引的列表。"
我的基本问题是我需要使用 2 个整数数组,并得到一个组合数组,它是使用 2 个初始数组的成对组合制成的许多范围的组合。
略有不同地说,我想使用2个数组,将它们组合起来产生一组范围,然后将这些范围合并在一起。重要的是,我需要在不使用任何循环的情况下执行此操作,因为我将需要执行将近 400 万次。
我的 2 个起始数组是:
import numpy as np
sd = np.array([3,3,4,2,5,1]) # StartDate
ed = np.array([4,5,5,5,8,2]) # EndDate
成对地,它们看起来像这样,结合(sd[i] 和 ed[i]):
[(3, 4), (3, 5), (4, 5), (2, 5), (5, 8), (1, 2)] # Pairwise combinations of StartDate and EndDate
举例来说,我可以迭代这些对,创建范围,示例如下:
[In]: range1 = np.arange(3,4)
[Out]: array([3])
[In]: range2 = np.arange(3,5)
[Out]: array([3,4])
...依此类推,得出最终输出:
array([3, 3, 4, 4, 2, 3, 4, 5, 6, 7, 1]) # End result where the arrays are tiled after one another
#(note first 3 digits are array 1 and array 2 from immediately above.
我的问题是我需要在不循环的情况下从输入数组转到输出数组,因为我已经尝试过这个版本,而且速度太慢了。非常感谢任何帮助。
你很幸运。这是一个单行解决方案:
indexer = np.r_[tuple([np.s_[i:j] for (i,j) in zip(sd,ed)])]
输出:
[3 3 4 4 2 3 4 5 6 7 1]
np.s_[i:j] 创建一个从 start=i 到 end=j 的索引的切片对象(只是一个范围)。
np.r_[i:j, k:m] 创建切片 (i,j) 和 (k,m) 中的所有索引列表(您可以将更多切片传递给 np.r_ 将它们一次连接在一起。这是仅连接两个切片的示例。)
因此,索引器通过连接切片列表(每个切片是一个索引范围)来创建所有索引的列表。"