我有一个由5个值组成的数组,由4个值和一个索引组成。我沿着索引对数组进行排序和拆分。这导致我分裂不同长度的矩阵。从这里开始,我想计算每个分裂的第四个值的均值,方差和前三个值的协方差。我当前的方法适用于for循环,我想用矩阵运算代替它,但我对我的矩阵的不同大小感到困惑。
import numpy as np
A = np.random.rand(10,5)
A[:,-1] = np.random.randint(4, size=10)
sorted_A = A[np.argsort(A[:,4])]
splits = np.split(sorted_A, np.where(np.diff(sorted_A[:,4]))[0]+1)
我当前的for循环看起来像这样:
result = np.zeros((len(splits), 5))
for idx, values in enumerate(splits):
if(len(values))>0:
result[idx, 0] = np.mean(values[:,3])
result[idx, 1] = np.var(values[:,3])
result[idx, 2:5] = np.cov(values[:,0:3].transpose(), ddof=0).diagonal()
else:
result[idx, 0] = values[:,3]
我尝试使用蒙面数组但没有成功,因为我无法以适当的形式将矩阵加载到蒙版数组中。也许有人知道该怎么做或有不同的建议。
答案 0 :(得分:2)
您可以按如下方式使用np.add.reduceat
:
>>> idx = np.concatenate([[0], np.where(np.diff(sorted_A[:,4]))[0]+1, [A.shape[0]]])
>>> result2 = np.empty((idx.size-1, 5))
>>> result2[:, 0] = np.add.reduceat(sorted_A[:, 3], idx[:-1]) / np.diff(idx)
>>> result2[:, 1] = np.add.reduceat(sorted_A[:, 3]**2, idx[:-1]) / np.diff(idx) - result2[:, 0]**2
>>> result2[:, 2:5] = np.add.reduceat(sorted_A[:, :3]**2, idx[:-1], axis=0) / np.diff(idx)[:, None]
>>> result2[:, 2:5] -= (np.add.reduceat(sorted_A[:, :3], idx[:-1], axis=0) / np.diff(idx)[:, None])**2
>>>
>>> np.allclose(result, result2)
True
请注意,协方差矩阵的对角线只是差异,这简化了这种矢量化。