简体   繁体   English

NumPy:按np.array过滤行

[英]NumPy: filter rows by np.array

I'd like to filter a NumPy 2-d array by checking whether another array contains a column value. 我想通过检查另一个数组是否包含列值来过滤NumPy 2-d数组。 How can I do that? 我怎样才能做到这一点?

import numpy as np

ar = np.array([[1,2],[3,-5],[6,-15],[10,7]])
another_ar = np.array([1,6])
new_ar = ar[ar[:,0] in another_ar]
print new_ar

I hope to get [[1,2],[6,-15]] but above code prints just [1,2] . 我希望得到[[1,2],[6,-15]]但是上面的代码仅显示[1,2]

You can use np.where ,but note that as ar[:,0] is a list of first elements if ar you need to loop over it and check for membership : 您可以使用np.where ,但请注意,如果ar需要循环遍历并检查成员身份,则ar[:,0]是第一个元素的列表:

>>> ar[np.where([i in another_ar for i in ar[:,0]])]
array([[  1,   2],
       [  6, -15]])

Instead of using in , you can use np.in1d to check which values in the first column of ar are also in another_ar and then use the boolean index returned to fetch the rows of ar : 您可以使用np.in1d来检查ar第一列中的哪些值也位于another_ar in ,而不是使用in ,然后使用返回的布尔值索引来获取ar的行:

>>> ar[np.in1d(ar[:,0], another_ar)]
array([[  1,   2],
       [  6, -15]])

This is likely to be much faster than using any kind of for loop and testing membership with in . 这可能比使用任何类型的for循环和in测试成员资格要快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM