Home > Mobile >  Vectorize a for loop based on condition using numpy
Vectorize a for loop based on condition using numpy

Time:01-03

I have 2 numpy arrays l1 and l2 as follows:

start, jump = 1, 2
L = 8

l1 = np.arange(start, L)
l2 = np.arange(start   jump, L jump)

This results in:

l1 = [1 2 3 4 5 6 7]
l2 = [3 4 5 6 7 8 9]

Now, I want 2 resultant arrays r1 and r2 such that while appending elements of l1 and l2 one by one in r1 and r2 respectively, it should check if r2 does not contain $i^{th}$ element of l1.

Implementing this using for loop is easy. But I am stuck on how to implement it using only numpy (without using loops) as I am new to it.

This is what I tried and want I am expecting:

r1 = []
r2 = []

for i in range(len(l1)):
    if (l1[i] not in r2):
        r1.append(l1[i])
        r2.append(l2[i])

This gives:

r1 = [1, 2, 5, 6]
r2 = [3, 4, 7, 8]

Thanks in advance :)

CodePudding user response:

As suggested by @Chrysoplylaxs in comments, I made a boolean mask and it worked like a charm!

mask = np.tile([True]*jump   [False]*jump, len(l1)//jump).astype(bool)
r1 = l1[mask[:len(l1)]]
r2 = l2[mask[:len(l2)]]
  • Related