numpy np数组在列表中计算平均值

zf2sa74q  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(104)

我试图计算每个嵌套列表的平均值:

import numpy as np
centroids = [[[3, 2]], [[2, 3], [3, 4], [2, 3]], [[1, 2], [3, 4]]]

所以我希望这些列的平均值如下:[3, 2][[2, 3], [3, 4], [2, 3]] = [2.3, 3.3][[1, 2], [3, 4]] = [2, 3]
我试着去做:

for c in centroids:
    c = np.mean(np.array(c), axis=0)

但它不起作用,质心列表中没有任何变化。怎么做?

eqoofvh9

eqoofvh91#

使用简单的列表理解来收集方法:

centroids = [np.mean(a, 0).tolist() for a in centroids]
[[3.0, 2.0], [2.3333333333333335, 3.3333333333333335], [2.0, 3.0]]
n3h0vuf2

n3h0vuf22#

一个vanilla python实现:

centroids = [[[3, 2]], [[2, 3], [3, 4], [2, 3]], [[1, 2], [3, 4]]]
means = list()
for centroid in centroids:
    pair = [0, 0]
    for centroidPair in centroid:
        pair[0] += centroidPair[0]
        pair[1] += centroidPair[1]
    pair[0] /= len(centroid)
    pair[1] /= len(centroid)
    means.append(pair);
print(means);

它输出预期结果:

[[3.0, 2.0], [2.3333333333333335, 3.3333333333333335], [2.0, 3.0]]

相关问题