使用掩蔽数组行计算数组行的平均值

2024-09-30 01:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在将这行简单的倍频程代码转换为Python时,我想知道是否有一种更快/更干净的方法:

给定两个矩阵,Octave命令将一行矩阵Y平均,使用布尔矩阵R标记感兴趣的值:

load (‘mydata.mat’)
row1_mean = mean( Y(1, R(1, :) ) )

又好又快又简单。在Python中尝试这样做要简洁得多,但到目前为止,我可以这样做:

import numpy as np
from scipy import io as spio

myDict = spio.loadmat(‘mydata.mat’)
Y_mat = myDict['Y']
R_mat = myDict['R']

maskR = ~R_mat.astype(bool)[0][:]                      # row as boolean so we can invert it
maskR = maskR.astype(int)                              # turn it back to 1s & 0s

maskedY = np.ma.masked_array(Y_mat[0][:], mask=maskR)  # mask row of Y with R matrix

row1_mean = maskedY.mean()                             # get the mean

我可能错过了一个更好的方法。 特别是,有没有一种更简单的方法来反转1和0的矩阵? 也许还有一种更直接的方法来获得数组切片的平均值(我知道axis),但是考虑到掩蔽数组?你知道吗


Tags: 方法importasnpit矩阵meanmydict
2条回答

如果要使用掩蔽数组,以下是一种简化的方法:

import numpy as np

# create some mock data
R_mat = np.arange(16).reshape(4, 4)
Y_mat = np.random.randint(0, 2, (4, 4))

R_mat
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11],
#        [12, 13, 14, 15]])
Y_mat
# array([[0, 1, 0, 1],
#        [0, 1, 1, 0],
#        [0, 1, 0, 1],
#        [0, 0, 1, 0]])

# compute all row means or all column means at once
# use Y_mat==0 to invert and convert to bool in one go
row_means = np.ma.MaskedArray(R_mat, Y_mat==0).mean(axis=1)
col_means = np.ma.MaskedArray(R_mat, Y_mat==0).mean(axis=0)

row_means
# masked_array(data=[2.0, 5.5, 10.0, 14.0],
#              mask=[False, False, False, False],
#        fill_value=1e+20)
col_means
# masked_array(data=[ , 5.0, 10.0, 7.0],
#              mask=[ True, False, False, False],
#        fill_value=1e+20)


# or take just one row or column and get the mean 
np.ma.MaskedArray(R_mat, Y_mat==0)[2].mean()
# 10.0
np.ma.MaskedArray(R_mat, Y_mat==0)[:, 0].mean()
# masked

如果出于某种原因要避免使用屏蔽数组:

nrow, ncol = R_mat.shape

I, J = np.where(Y_mat)
row_means = np.bincount(I, R_mat[I, J], nrow) / np.bincount(I, None, nrow)

J, I = np.where(Y_mat.T)
col_means = np.bincount(J, R_mat[I, J], ncol) / np.bincount(J, None, ncol)
# __main__:1: RuntimeWarning: invalid value encountered in true_divide

row_means
# array([ 2. ,  5.5, 10. , 14. ])
col_means
# array([nan,  5., 10.,  7.])

把蒙面的卑鄙和裸体结合起来

如果我理解你的正确做法,这里有一个更好的方法:

row1_mean = Y_mat[0][R_mat[0].astype(bool)].mean()

如果你只想知道一行的平均值。您可以这样计算每行的平均值:

means = np.nanmean(np.where(mask, arr, np.nan), axis=1)
# if every value in a given row is masked, the mean will be calculated as nan. Change those to zeros
means[np.isnan(means)] = 0

Numpy中的布尔索引

作为将来使用的注意事项,您实际上可以使用布尔数组索引Numpy数组(就像倍频程,我猜?)。下面是一个简单的例子:

import numpy as np

arr = np.arange(10*5).reshape(10,5)
mask = np.random.randint(0, 2, (10, 5), dtype=bool)

print('original array\n%s\n' % arr)
print('boolean masked array\n%s\n' % arr[mask])

输出:

original array
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]
 [25 26 27 28 29]
 [30 31 32 33 34]
 [35 36 37 38 39]
 [40 41 42 43 44]
 [45 46 47 48 49]]

boolean masked array
[ 1  2  3  4  7  8 10 11 12 14 15 19 26 27 29 33 38 39 44 45 46]

如您所见,布尔索引将使二维数组变平(这是paulpanzer在注释中解释的原因)。这就是我在上面第二个答案中使用np.where的原因。你知道吗

相关问题 更多 >

    热门问题