简体   繁体   English

Python 过滤器 numpy 数组基于掩码数组

[英]Python filter numpy array based on mask array

Let's say I have an data numpy array of length N, and a bit mask array of length N.假设我有一个长度为 N 的数据 numpy 数组和一个长度为 N 的位掩码数组。

data = [1,2,3,4,5,6,7,8,9,0]
mask = [0,1,0,1,0,1,0,1,0,1]

Is there a loopless numpy way to create a new array based off data, such that it takes all the entries of data if and only if masks[i]?= 0: Like so:是否有一种无循环的 numpy 方法来创建一个基于数据的新数组,这样当且仅当 mask[i]?= 0 时它才会获取所有数据条目:像这样:

func(data, mask) = [2,4,6,8,0]

Or equivalently in loop notation:或等效地在循环符号中:

ans = []
for idx in range(mask):
    if mask[idx]:
        ans.append(data[idx])
ans = numpy.array(ans)

Thanks!谢谢!

You can filter numpy arrays with an array of boolean values.您可以使用一组 boolean 值过滤 numpy arrays 。 You are starting with an array of integers, which you can't use directly, but you can of course interpret the ones and zeros as booleans and then use it directly as a mask:您从一个整数数组开始,您不能直接使用它,但您当然可以将 1 和 0 解释为布尔值,然后直接将其用作掩码:

import numpy as np

data = np.array([1,2,3,4,5,6,7,8,9,0])
mask = np.array([0,1,0,1,0,1,0,1,0,1])

data[mask.astype(bool)]
# array([2, 4, 6, 8, 0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM