繁体   English   中英

计算 Numpy 矩阵中每一行的平均值

[英]Compute the mean of each row in a Numpy Matrix

我想实现执行以下操作的 phython 代码:

 For a collections of clusters calculate the mean for each cluster

Args:
    clusters (List[np.ndarray]): A list of 2d arrays
    
Returns:
    List[np.ndarray]: A matrix where each row represents a mean of a cluster
    
Example: 
    >>> tiny_clusters = [
        np.array([[0.2, 0.3], [0.1, 0.2]]),
        np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
    ]
    >>> calc_means(tiny_clusters)
    [array([0.15, 0.25]), array([0.7,0.7])]

我目前的解决方案如下:

    i = 0 
    return [clusters[i].mean(axis=1) for i in range(np.amax(i)+1)]

但是,我只得到以下 output:

    [array([0.25, 0.15])]

    (Input: [
    np.array([[0.2, 0.3], [0.1, 0.2]]),
    np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
    ])

所以,我只计算了第一行的平均值,但不幸的是第二行没有。 你有什么想法可以改进我的代码吗?

谢谢!

列表理解应该是

[q.mean(axis=0) for q in clusters]

output被称为矩阵有点令人困惑。 它是等级 1 arrays 的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM