[英]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]
。
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.