1

如何计算大数组中每三个数组的平均值?

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]"
4

2 回答 2

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])
于 2013-11-08T04:27:25.330 回答
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]
于 2013-11-08T04:40:23.327 回答