Reputation: 165
I have 2 numpy arrays: b
and s
. And len(b)==2*len(s)
.
s
has the form:
l r l r l r ...
I what to transform it into:
0 0 l r 0 0 l r 0 0 l r ...
I'm doing it the easy way:
ix = 0
jx = 0
while ix < len(b):
b[ix] = 0
ix += 1
b[ix] = 0
ix += 1
b[ix] = s[jx]
ix += 1
jx += 1
b[ix] = s[jx]
ix += 1
jx += 1
For speed, I'd like to do the same using numpy api but can't get something working.
What numpy methods should I be using?
Upvotes: 2
Views: 117
Reputation: 231385
Based on the repetition in b
and s
, I automatically see a 2d solution:
b = np.zeros(N,4)
b[:,2:] = s.reshape(N,2)
b = b.flatten()
or appending the 0s onto the reshaped s
:
b = np.hstack([np.zeros((10,2)),s.reshape(10,2)]).flatten()
or if we want to think in 3d
np.einsum('ij,k->ikj',s.reshape(N,2),[0,1]).flatten()
Same but with broadcasting
(s.reshape(10,2)[:,None,:]*np.array([0,1])[None,:,None]).flatten()
Upvotes: 1
Reputation: 65791
May not be the smartest solution, but you can do it in two passes similar to this answer:
In [1]: import numpy as np
In [2]: s = np.array([1, 2] * 3)
In [3]: b = np.zeros(2 * s.size)
In [4]: b[2::4] = s[::2]
In [5]: b[3::4] = s[1::2]
In [6]: b
Out[6]: array([ 0., 0., 1., 2., 0., 0., 1., 2., 0., 0., 1., 2.])
Upvotes: 3