Вот векторизация с использованием 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