如何使用另一个数组的值过滤一个numpy数组? [英] How to filter a numpy array using another array's values?
本文介绍了如何使用另一个数组的值过滤一个numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个NumPy数组,例如:
I have two NumPy arrays, e.g.:
a = [1,2,3,4,5]
和一个过滤器数组,例如:
and a filter array, e.g.:
f = [False, True, False, False, True]
len(a) == len(f)
如何获取仅具有f
中相同索引为True的值的新numpy数组?就我而言:[2, 5]
.
How can I get a new numpy array with only the values in a where the same index in f
is True? In my case: [2, 5]
.
根据接受的解决方案(具有不同的值):
According to the accepted solution (with different values):
>>> a = numpy.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = numpy.array([True, False, True, False, True, False, True, False, True, False])
>>> a[b]
array([1, 3, 5, 7, 9])
推荐答案
NumPy支持这假定a
和f
是NumPy数组而不是Python列表(如问题所示).您可以使用f = np.array(f)
进行转换.
This assumes that a
and f
are NumPy arrays rather than Python lists (as in the question). You can convert with f = np.array(f)
.
这篇关于如何使用另一个数组的值过滤一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文