给出此数组X:
[1 2 3 2 3 1 4 5 7 1]
和行长数组R:
[3 2 5]
表示转换后每一行的长度。
我正在寻找一种计算效率高的函数来将X重整为该数组Y:
[[ 1. 2. 3. nan nan]
[ 2. 3. nan nan nan]
[ 1. 4. 5. 7. 1.]]
这些只是我正在处理的实际数组的简化版本。我的实际数组更像这样:
R = np.random.randint(5, size = 21000)+1
X = np.random.randint(10, size = np.sum(R))
我已经掌握了一个生成变形数组的函数,但是该函数运行太慢。我已经尝试了一些Numba功能来加快速度,但是它们会产生许多错误消息来处理。我的超级慢功能:
def func1(given_array, row_length):
corresponding_indices = np.cumsum(row_length)
desired_result = np.full([len(row_length),np.amax(row_length)], np.nan)
desired_result[0,:row_length[0]] = given_array[:corresponding_indices[0]]
for i in range(1,len(row_length)):
desired_result[i,:row_length[i]] = given_array[corresponding_indices[i-1]:corresponding_indices[i]]
return desired_result
当input_arrays的大小尚未超过100K时,此函数每个循环要花费34ms的艰巨时间。我正在寻找一个功能,该功能以相同的大小执行相同的操作,但每个循环的时间少于10ms
提前谢谢
答案 0 :(得分:1)
这是一个利用broadcasting
-向量的人-
def func2(given_array, row_length):
given_array = np.asarray(given_array)
row_length = np.asarray(row_length)
mask = row_length[:,None] > np.arange(row_length.max())
out = np.full(mask.shape, np.nan)
out[mask] = given_array
return out
样品运行-
In [305]: a = [1, 2, 3, 2, 3, 1, 4, 5, 7, 1]
...: b = [3, 2, 5]
In [306]: func2(a,b)
Out[306]:
array([[ 1., 2., 3., nan, nan],
[ 2., 3., nan, nan, nan],
[ 1., 4., 5., 7., 1.]])
大型数据集的时间和验证-
In [323]: np.random.seed(0)
...: R = np.random.randint(5, size = 21000)+1
...: X = np.random.randint(10, size = np.sum(R))
In [324]: %timeit func1(X,R)
100 loops, best of 3: 17.5 ms per loop
In [325]: %timeit func2(X,R)
1000 loops, best of 3: 657 µs per loop
In [332]: o1 = func1(X,R)
In [333]: o2 = func2(X,R)
In [334]: np.allclose(np.where(np.isnan(o1),0,o1),np.where(np.isnan(o2),0,o2))
Out[334]: True