我有一个包含1000行和10列的数组(price_list)。使用命令
price_list.mean(axis = 1)
我对每一行进行均值。如何使用循环执行相同的计算?非常感谢。
示例:
In: price_list
Out: array([[ 88.118629 , 88.118629 , 88.118629 , ..., 88.118629 ,
88.118629 , 88.118629 ],
[ 87.89849451, 88.28521857, 87.88550764, ..., 88.63412578,
88.10322998, 88.88926288],
[ 88.65587777, 87.76942845, 88.48962856, ..., 88.2796555 ,
88.63031452, 88.88182671],
...,
[ 65.34289835, 66.92005094, 90.12852383, ..., 167.15607114,
226.66403648, 130.07803463],
[ 65.55047596, 66.5069593 , 88.99919496, ..., 164.45858893,
229.17325779, 129.15578263],
[ 64.71865904, 66.40562405, 88.06256922, ..., 161.90378821,
227.48460064, 127.58404374]])
In: price_list_new = price.list.mean(axis = 1)
Out: array([ 88.118629 , 88.35964886, 88.36762515, 88.82571439,
89.15239399, 88.74944235, 88.82604126, 88.48155552,
88.70669718, 88.87349793, 88.49569989, 88.3928375 ,
88.44854633, 88.38734393, 88.51877214, 88.53055382,
88.47660207, 88.08328303, 88.05407612, 87.73566519,
88.10523588, 87.72906819, 87.53641688, 87.5564761 ,
87.4484196 , .............])
答案 0 :(得分:0)
首先,我创建一个伪造的price_list
:
import numpy as np
price_list = np.random.rand(10,1000)
price_list.mean(axis = 1)
#> array([0.49730006, 0.48494404, 0.4948243 , 0.49762745, 0.49727592,
#> 0.50856465, 0.4993344 , 0.49325429, 0.4938947 , 0.50599995])
现在,我们可以使用向量化数组进行一次循环:
price_list_mean = np.zeros(10)
for i in range(price_list.shape[1]):
price_list_mean = price_list_mean + price_list[:,i]
price_list_mean = price_list_mean/price_list.shape[1]
# Checking the solution
np.isclose(price_list_mean,price_list.mean(axis = 1))
#> array([ True, True, True, True, True, True, True, True, True, True])
或者我们可以使用双循环来实现:
price_list_mean = np.zeros(10)
for j in range(price_list.shape[0]):
for i in range(price_list.shape[1]):
price_list_mean[j] = price_list_mean[j] + price_list[j,i]
price_list_mean[j] = price_list_mean[j] / price_list.shape[1]
# Checking the solution
np.isclose(price_list_mean,price_list.mean(axis = 1))
#> array([ True, True, True, True, True, True, True, True, True, True])
警告!:这些解决方案比仅通过函数计算均值要低得多。除非用于教学目的,否则不应使用它们。
答案 1 :(得分:0)
price_list.mean(axis = 1)
# array([ 3.5, 11.5, 19.5, 27.5, 35.5])
可以通过遍历numpy数组并计算每行的平均值来完成此操作。
for i in price_list:
print(i.mean())
或
[i.mean() for i in price_list]