Reputation: 1518
Given this array X:
[1 2 3 2 3 1 4 5 7 1]
and the row length array R:
[3 2 5]
that represents the lengths of each row after the transformation.
I am looking for a computationally efficient function to reshape X into this array Y:
[[ 1. 2. 3. nan nan]
[ 2. 3. nan nan nan]
[ 1. 4. 5. 7. 1.]]
These are merely simplified version of the actual arrays I am working on. My actual arrays are more like this:
R = np.random.randint(5, size = 21000)+1
X = np.random.randint(10, size = np.sum(R))
I have already got down a function to generate the reshaped array, but the function runs way too slow. I have tried some Numba features to speed it up, but they generate to many error messages to handle. My super slow function:
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
This function takes a daunting 34ms per loop when the sizes of the input_arrays haven't exceeded 100K yet. I am looking for a function that does the same thing with the same sizes but in under 10ms per loop
Thank you in advance
Upvotes: 1
Views: 55
Reputation: 221524
Here's a vectorized one leveraging 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
Sample run -
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.]])
Timings and verification on large dataset -
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
Upvotes: 1