如何计算大数组中每三个数组的平均值?
my_array = [[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6]]
numpy_array = np.array(my_array)
mean_each_array= [np.mean (x) for x in numpy_array]
result_mean_each_array = [1,2,3,4,5,6] #OK
mean_every_three_arrays = ???
result_mean_every_three_arrays = [2,5] how?
"I want to calculate mean of [1,1,1],[2,2,2],[3,3,3] and [4,4,4],[5,5,5],[6,6,6]"
答案 0 :(得分:2)
import numpy as np
my_array = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6]])
reshaped = my_array.reshape(2, -1)
result = np.mean(reshaped, axis=1)
结果:
>>> reshaped
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]])
>>> result
array([ 2., 5.])
作为旁注,您不需要遍历数组就可以获得每行的均值:
>>> np.mean(my_array, axis=1) # gives you a mean for each row
array([ 1., 2., 3., 4., 5., 6.])
>>> np.mean(my_array, axis=0) # gives you a mean for each column
array([ 3.5, 3.5, 3.5])
答案 1 :(得分:1)
我明白了 - 重塑阵列!
import numpy as np
my_array = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6]])
new_array = my_array.reshape(9, 2)
result= [np.mean (x) for x in new_array]
print (result)
[2.0, 5.0]