如何使用另一个数组的值过滤一个 numpy 数组? [英] How to filter a numpy array using another array's values?

查看:38
本文介绍了如何使用另一个数组的值过滤一个 numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 NumPy 数组,例如:

a = [1,2,3,4,5]

和一个过滤器数组,例如:

f = [假,真,假,假,真]len(a) == len(f)

如何获得一个新的 numpy 数组,其中只有 f 中的相同索引为 True 中的值?就我而言:[2, 5].

根据接受的解决方案(具有不同的值):

<预><代码>>>>a = numpy.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])>>>b = numpy.array([真、假、真、假、真、假、真、假、真、假])>>>[b]数组([1, 3, 5, 7, 9])

解决方案

NumPy 支持 布尔索引

a[f]

这假设 af 是 NumPy 数组而不是 Python 列表(如问题所示).您可以使用 f = np.array(f) 进行转换.

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)

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 supports boolean indexing

a[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆