在for循环中对NumPy数组进行平均化?

huangapple go评论61阅读模式
英文:

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

尝试这个 -

  1. 在每次迭代中将array_that_I_calculate附加到list_of_arrays
  2. 循环结束后,对list_of_arraysaxis=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 -

  1. Append the array_that_I_calculate at each iteration into a list_of_arrays
  2. After the loop ends, take np.average() of list_of_arrays over axis=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)

huangapple
  • 本文由 发表于 2023年1月9日 19:33:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定