Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple numpy masks

Tags:

python

numpy

m1 = [0,1,1,3]
m2 = [0,0,1,1]
data = [10,20,30,40]

I want to do something like this:

mask = (m1 == 1) & (m2 == 1)
data[mask] #should return 30

Note, this example results in an error

like image 258
siamii Avatar asked Mar 22 '13 20:03

siamii


1 Answers

You are using python lists instead of numpy arrays. Try this instead:

import numpy as np

m1 = np.array([0,1,1,3])
m2 = np.array([0,0,1,1])

mask = (m1 == 1) & (m2 == 1)
data[mask]
# returns array([30])

In your example, when m1 was a list, m1 == 1 is evaluated as False (the same for m2), so mask was False and data[False] = data[0] = 10.

like image 123
tiago Avatar answered Sep 18 '22 14:09

tiago