numpy阵列多重面膜 [英] Numpy array multiple mask
本文介绍了numpy阵列多重面膜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试基于整数掩码数组多次对numpy数组进行切片和平均:
Trying to slice and average a numpy array multiple times, based on an integer mask array:
即
import numpy as np
data = np.arange(11)
mask = np.array([0, 1, 1, 1, 0, 2, 2, 3, 3, 3, 3])
results = list()
for maskid in range(1,4):
result = np.average(data[mask==maskid])
results.append(result)
output = np.array(result)
有没有一种方法可以更快地执行此操作,而又没有"for"循环?
Is there a way to do this faster, aka without the "for" loop?
推荐答案
使用另一种具有 np.unique
用于一般情况,其中mask
中的元素不一定是从0
-
Another one with np.unique
for a generic case when the elements in mask
aren't necessarily sequential starting from 0
-
_,ids, count = np.unique(mask, return_inverse=1, return_counts=1)
out = np.bincount(ids, data)/count
这篇关于numpy阵列多重面膜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文