numpy 如何将子数组中的值更改为这些值的平均值?

t40tm48m  于 2023-10-19  发布在  其他
关注(0)|答案(3)|浏览(121)

我有一个数组:

  1. > a
  2. array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

我想将这些值更改为这些值的平均值,因此输出将是:

  1. > a
  2. array([[2, 2, 2], [3, 3, 3], [4, 4, 4]])

有没有一种不使用for循环的快速方法?

l2osamch

l2osamch1#

如果你能够使用numpy模块,broadcasting函数对此很有用(尽管它们也是通过高度优化的循环来实现的)。
a.mean(axis=1)获取行平均值,np.broadcast_to将结果广播到所需的形状。.T只返回结果的转置

  1. import numpy as np
  2. a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
  3. np.broadcast_to(a.mean(axis=1), a.shape).T

输出量:

  1. array([[2., 2., 2.],
  2. [3., 3., 3.],
  3. [4., 4., 4.]])
epggiuax

epggiuax2#

另一种可能的解决方案:

  1. n = a.shape[1]
  2. np.repeat(a.mean(axis=1), n).reshape(-1, n)

输出量:

  1. array([[2., 2., 2.],
  2. [3., 3., 3.],
  3. [4., 4., 4.]])
qybjjes1

qybjjes13#

  • "....."*

你可以使用 list comprehension
注意,我在这里使用 int 函数,因为你提供的数据是非分数的。

  1. a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
  2. a = [([int(sum(x) / len(x))] * 3) for x in a]

输出

  1. [[2, 2, 2], [3, 3, 3], [4, 4, 4]]

相关问题