numpy conditional list membership element wise


I have a 2D numpy array:



I have a list of values to keep:



I want to test for list membership for each element in the array. Something like:



The result I want:



You can use isin



isin is an element-wise function version of the python keyword in



An added benefit of isin is that it's flexible with arrays of different dimensions:



Here is one way using broadcasting:



Which is faster than isin for small arrays (less than 100 rows):



For large arrays it's better to use isin because broadcasting in 3D is not very efficient for large arrays/matrices.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

大跃进

马相伯