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

zf2sa74q  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(158)

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

  1. import numpy as np
  2. 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]
我试着去做:

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

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

eqoofvh9

eqoofvh91#

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

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

n3h0vuf22#

一个vanilla python实现:

  1. centroids = [[[3, 2]], [[2, 3], [3, 4], [2, 3]], [[1, 2], [3, 4]]]
  2. means = list()
  3. for centroid in centroids:
  4. pair = [0, 0]
  5. for centroidPair in centroid:
  6. pair[0] += centroidPair[0]
  7. pair[1] += centroidPair[1]
  8. pair[0] /= len(centroid)
  9. pair[1] /= len(centroid)
  10. means.append(pair);
  11. print(means);

它输出预期结果:

  1. [[3.0, 2.0], [2.3333333333333335, 3.3333333333333335], [2.0, 3.0]]

相关问题