(n + 1)-dim布尔值,将带有均值数组的n-dim数组掩盖为所需的输出 [英] (n+1)-dim boolean masking a n-dim array with array of means as desired output
问题描述
我有一个带有值的2D数组
I have this 2D-array with values
values=np.random.rand(3,3)
和带有布尔蒙版的3D阵列
and a 3D-array with boolean masks
masks = np.random.rand(5,3,3)>0.5
我想要的输出是掩码值均值的数组.我可以这样:
My desired output is an array of the means of the masked values. I can do that with:
np.array([values[masks[i]].mean() for i in range(len(masks))])
有没有更有效的方法来实现这一目标?
Is there a more efficient way of achieving that ?
推荐答案
You could use matrix-multplication
with np.dot
like so -
# Counts of valid mask elements for each element in output
counts = masks.sum(axis=(1,2))
# Use matrix multiplication to get sum of elementwise multiplications.
# Then, divide by counts for getting average/mean values as final output.
out = np.dot(masks.reshape(masks.shape[0],-1),values.ravel())/counts
也可以使用 np.tensordot
执行点积而无需重塑,就像这样-
One can also use np.tensordot
to perform the dot-product without reshaping, like so -
out = np.tensordot(masks,values,axes=([1,2],[0,1]))/counts
对于涉及诸如min()
& max()
,您可以将values
广播到具有与masks
相同形状的3D
阵列版本,并且将元素从values
设置在True
位置,否则设置为NaNs
.然后,您可以使用类似 np.nanmin
和 np.nanmax
允许用户忽略NaNs
执行此类操作,从而复制我们所需的行为.因此,我们将有-
For generic cases involving functions like min()
& max()
, you can broadcast values
to a 3D
array version of the same shape as masks
and with elements set from values
at True
positions, otherwise set as NaNs
. Then, you can use functions like np.nanmin
and np.nanmax
that allows users to perform such operations ignoring the NaNs
, thus replicating our desired behavior. Thus, we would have -
# Masked array with values being put at True places of masks, otherwise NaNs
nan_masked_values = np.where(masks,values,np.nan)
# For performing .min() use np.nanmin
out_min = np.nanmin(nan_masked_values,axis=(1,2))
# For performing .max() use np.nanmax
out_max = np.nanmax(nan_masked_values,axis=(1,2))
Thus, the original .mean()
calculation could be performed with np.nanmean
like so -
out_mean = np.nanmean(nan_masked_values,axis=(1,2))
这篇关于(n + 1)-dim布尔值,将带有均值数组的n-dim数组掩盖为所需的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!