2

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?

2 Answers 2

3

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.])
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.