【问题标题】:Index numpy array by multiple boolean masks [duplicate]通过多个布尔掩码索引numpy数组[重复]
【发布时间】:2019-11-04 19:03:10
【问题描述】:

我有一个数组 x 和一个过滤器列表(布尔数组的长度与 x 相同):

x = np.random.rand(10)
filt1 = x > .2
filt2 = x < .5
filt3 = x % 2 > .02
filters_list = [filt1, filt2, filt3]

我想创建一个过滤器,它是filters_list 中所有过滤器的逻辑与,所以输出应该是

output = x[filt1 & filt2 & filt3]

假设len(filters_list) 是任意的,我如何从filters_list 创建过滤器filt1 &amp; filt2 &amp; filt3

【问题讨论】:

  • np.logical_and

标签: python arrays numpy boolean-logic


【解决方案1】:

您可以将numpy.all() 与轴和过滤器列表一起使用。

x = np.arange(10)
filt1 = x > 2
filt2 = x < 9
filt3 = (x % 2) == 1
filters_list = np.all([filt1, filt2, filt3], axis=0)
x[filters_list]

#array([3, 5, 7])

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2011-11-03
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2020-01-14
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多