簡體   English   中英

有沒有辦法矢量化將平均 function 應用於 ndarray 中的屏蔽區域?

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

假設我有兩個 ndarray 定義如下:

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

我的目標是根據掩碼中的 integer 指示的mask區域計算值的平均值。 自然,我會使用 for 循環:

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

但是,對於大型多維 arrays,此序列化解決方案變得非常緩慢。 有沒有辦法有效地矢量化這個操作? 提前謝謝你的幫助!

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM