Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use numpy array to do conditional operations on another array

Let’s say I have 2 arrays:

a = np.array([2, 2, 0, 0, 2, 1, 0, 0, 0, 0, 3, 0, 1, 0, 0, 2])

b = np.array([0, 0.5, 0.25, 0.9])

What I would like to do, is take the value in array b and multiple it to the values in array a, based on it’s index.

So the first value in array a is 2. I want the value in array b at that index position to be multiplied by that value. So in array b, index postion 2’s value is 0.25, so multiple that value (2) in array a by 0.25.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know it can be done with iteration, but I’m trying to figure out how it’s done elmentwise operations.

Here’s the iteration way that I’ve done:

result = np.array([])
for idx in a:
    result = np.append(result, (b[idx] * idx))

To get the result:

print(result)
[0.5 0.5 0.  0.  0.5 0.5 0.  0.  0.  0.  2.7 0.  0.5 0.  0.  0.5]

What’s an elementwise equivalent?

>Solution :

Integer arrays can be used as indices in numpy. As a consequence, you can simply do something like this

b[a] * a

EDIT:

Just for completeness, your iterative solution triggers a new memory allocation every time append is called (see the ‘returns’ section of this page). Since you already now the shape of your output (i.e. a.shape), it’s much better to allocate the output array in advance, e.g. result = np.empty(a.shape) and then go through the cycle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading