英文:
Averaging numpy array over for loop?
问题
我正在每次循环迭代中计算一个NumPy数组。如何对其进行平均?
例如:
for i in range(5):
我计算的数组 = 一些计算(x, y, z)
英文:
I am calculating a numpy array each iteration of a for loop. How do I average that?
For example:
for i in range(5):
array_that_I_calculate = some_calculation(x,y,z)
答案1
得分: 2
尝试这个 -
- 在每次迭代中将
array_that_I_calculate
附加到list_of_arrays
- 循环结束后,对
list_of_arrays
在axis=0
上使用np.average()
import numpy as np
##### 忽略 #####
# 返回 (2000,1) 数组的虚拟函数
def some_calculation(x=None, y=None, z=None):
return np.random.random((2000, 1))
##### 解决方案 #####
list_of_arrays = [] #<-----
for i in range(5):
array_that_I_calculate = some_calculation(x, y, z)
list_of_arrays.append(array_that_I_calculate) #<-----
averaged_array = np.average(list_of_arrays, axis=0) #<-----
print(averaged_array.shape)
(2000,1)
英文:
Try this -
- Append the
array_that_I_calculate
at each iteration into alist_of_arrays
- After the loop ends, take
np.average()
oflist_of_arrays
overaxis=0
import numpy as np
##### IGNORE #####
#dummy function that returns (2000,1) array
def some_calculation(x=None,y=None,z=None)
return np.random.random((2000,1))
##### SOLUTION #####
list_of_arrays = [] #<-----
for i in range(5):
array_that_I_calculate = some_calculation(x,y,z)
list_of_arrays.append(array_that_I_calculate) #<-----
averaged_array = np.average(list_of_arrays, axis=0) #<-----
print(averaged_array.shape)
(2000,1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论