1

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

10
  • Are the arrays always range-like arrays? Commented Dec 30, 2022 at 16:30
  • This is also probably the most direct option, you could speed it up using a set, but I don't know if numpy vectorize operations are a good fit for it Commented Dec 30, 2022 at 16:41
  • Your problem is tough to vectorize because the required behavior for element i is dependent on the results of the computations done for the previous iterations. The for loop is probably the best you can do. Commented Dec 30, 2022 at 16:42
  • @DaniMesejo yes the arrays are always range like arrays Commented Dec 30, 2022 at 17:00
  • 1
    In that case, I suspect that r1 and r2 will always follow some sort of pattern dependent on start, jump and L. It might be most efficient to construct them directly using those values Commented Dec 30, 2022 at 17:09

1 Answer 1

1

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

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.