1

I struggle to write find the best "question" so please feel free to suggest another title.

Lets say I have a=np.array([5,3,2,4]) and b=np.array([1,2]) - I want to get a list of list (or np.arrays) with the value of a>b[i] i.e it can be written as a list comprehension

[a[i]>p for p in b] which returns

[np.array([True,True,True,True]), np.array([True,True,False,True])]. Since I have a rather large data set I hoped that there was a numpy function to do such, or is list comprehension the better way here?

1
  • If the array a is really large (close to your memory limit), you may want to process a > b[i] separately anyway and in that case I would look no further than a simple loop, which is slow but can have a small memory footprint. Otherwise, you can use broadcasting which is fast but has a large memory footprint. List-comprehension in this case has both disadvantages: slow and large memory footprint. Commented May 8, 2020 at 8:03

1 Answer 1

6

You can use numpy broadcasting for this, you just need to add an extra dimension into each of your arrays:

>>> a[None,:] > b[:,None]
array([[ True,  True,  True,  True],
       [ True,  True, False,  True]])
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.