gpt4 book ai didi

python - 计算大数组内某些数组的平均值

转载 作者:行者123 更新时间:2023-11-30 23:31:33 26 4
gpt4 key购买 nike

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

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

最佳答案

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])

关于python - 计算大数组内某些数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com