在将这行简单的倍频程代码转换为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
),但是考虑到掩蔽数组?你知道吗
如果要使用掩蔽数组,以下是一种简化的方法:
如果出于某种原因要避免使用屏蔽数组:
把蒙面的卑鄙和裸体结合起来
如果我理解你的正确做法,这里有一个更好的方法:
如果你只想知道一行的平均值。您可以这样计算每行的平均值:
Numpy中的布尔索引
作为将来使用的注意事项,您实际上可以使用布尔数组索引Numpy数组(就像倍频程,我猜?)。下面是一个简单的例子:
输出:
如您所见,布尔索引将使二维数组变平(这是paulpanzer在注释中解释的原因)。这就是我在上面第二个答案中使用
np.where
的原因。你知道吗相关问题 更多 >
编程相关推荐