简体   繁体   English

有没有办法矢量化将平均 function 应用于 ndarray 中的屏蔽区域?

[英]Is there a way to vectorize applying the mean function to masked regions in an ndarray?

Let's say I have a two ndarray define as such:假设我有两个 ndarray 定义如下:

import numpy as np
mask = np.array([[1,1],[1,2]])
values = np.array([[1., 3.],[2., 2.]])

My goal is to calculate the mean of the values based on the mask regions indicated by the integer in mask .我的目标是根据掩码中的 integer 指示的mask区域计算值的平均值。 Naturally, I would use a for-loop:自然,我会使用 for 循环:

out = np.zeros(len(np.unique(mask)))
for j,i in enumerate(np.unique(mask)):
  out[j] = np.nanmean(values[mask==i])

However, this serialized solution becomes very slow for large, multidimensional arrays.但是,对于大型多维 arrays,此序列化解决方案变得非常缓慢。 Is there a way to vectorize this operation efficiently?有没有办法有效地矢量化这个操作? Thank you for your help in advance!提前谢谢你的帮助!

You can use np.bincount :您可以使用np.bincount

unq,inv,cnt = np.unique(mask,return_inverse=1,return_counts=1)
np.bincount(inv,values.ravel())/cnt
# array([2., 2.])

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

相关问题 向量化在ndarray的子​​阵列上操作的函数 - vectorize a function operated on subarray of a ndarray 求带掩码元素的numpy ndarray的平均值 - Taking mean of numpy ndarray with masked elements 如何矢量化具有不同形状的ndarray作为参数的函数? - How to vectorize a function having ndarray of different shape as an argument? Numpy数组均值函数未在均值计算中排除遮罩元素 - Numpy array mean function did not exclude masked element in mean computation 使用 np.vectorize 将 function 应用于图像的所有像素(宽度、高度、3) - Applying function to all pixels of an image (width, height, 3) with np.vectorize 图像区域密度的矢量化计算 - Vectorize calculation of density of image regions 以索引为参数将映射函数应用于ndarray的每个成员 - Applying a mapping function to each member of an ndarray with indices as arguments 将 function 应用于 ndarray 的行 && 将 itertool object 转换为 numpy 数组 - applying a function to rows of a ndarray && converting itertool object to numpy array 将累积平均值 function 应用于分组 object - Applying cumulative mean function to a grouped object 给定两个矩阵和一个采用两个向量的函数,如何对矩阵中每对向量的函数均值进行向量化? - Given two matrices and a function that takes two vectors, how to vectorize mean of function for every pair of vectors from the matrices?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM