通过多个布尔掩码索引numpy数组

2024-10-05 14:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组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 & filt2 & filt3?你知道吗


Tags: 过滤器列表outputlennprandom数组逻辑
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:29

可以将^{}与轴和筛选器列表一起使用。你知道吗

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])

相关问题 更多 >