我有一个数组:
> aarray([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
> a
array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
我想将这些值更改为这些值的平均值,因此输出将是:
> aarray([[2, 2, 2], [3, 3, 3], [4, 4, 4]])
array([[2, 2, 2], [3, 3, 3], [4, 4, 4]])
有没有一种不使用for循环的快速方法?
for
l2osamch1#
如果你能够使用numpy模块,broadcasting函数对此很有用(尽管它们也是通过高度优化的循环来实现的)。a.mean(axis=1)获取行平均值,np.broadcast_to将结果广播到所需的形状。.T只返回结果的转置
numpy
a.mean(axis=1)
np.broadcast_to
.T
import numpy as npa = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])np.broadcast_to(a.mean(axis=1), a.shape).T
import numpy as np
a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
np.broadcast_to(a.mean(axis=1), a.shape).T
输出量:
array([[2., 2., 2.], [3., 3., 3.], [4., 4., 4.]])
array([[2., 2., 2.],
[3., 3., 3.],
[4., 4., 4.]])
epggiuax2#
另一种可能的解决方案:
n = a.shape[1]np.repeat(a.mean(axis=1), n).reshape(-1, n)
n = a.shape[1]
np.repeat(a.mean(axis=1), n).reshape(-1, n)
qybjjes13#
你可以使用 list comprehension。注意,我在这里使用 int 函数,因为你提供的数据是非分数的。
a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]a = [([int(sum(x) / len(x))] * 3) for x in a]
a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
a = [([int(sum(x) / len(x))] * 3) for x in a]
输出
[[2, 2, 2], [3, 3, 3], [4, 4, 4]]
3条答案
按热度按时间l2osamch1#
如果你能够使用
numpy
模块,broadcasting函数对此很有用(尽管它们也是通过高度优化的循环来实现的)。a.mean(axis=1)
获取行平均值,np.broadcast_to
将结果广播到所需的形状。.T
只返回结果的转置输出量:
epggiuax2#
另一种可能的解决方案:
输出量:
qybjjes13#
你可以使用 list comprehension。
注意,我在这里使用 int 函数,因为你提供的数据是非分数的。
输出