【问题标题】:How do you calc the mean along an axis of numpy array? [duplicate]你如何计算沿numpy数组轴的平均值? [复制]
【发布时间】:2021-09-11 23:58:25
【问题描述】:

我是 python 新手。

这是我的三维数组:

my_data=numpy.zeros((index1,index2,index3))

为了说明,假设尺寸为:

index1 = 5
index2 = 4
index3 = 100

我想计算给定 index2 值的所有 index3 值的平均值。

我尝试了各种选择:

# Does not work
result[index1][index2] = numpy.mean(my_data[index1][index2][index3], axis=2)

# Also does not work
result = numpy.zeros((index1, index2))
result[index1][index2] = numpy.mean(my_data[index1][index2])

我错过了什么?

【问题讨论】:

  • 你能分享你得到的错误吗?
  • items *= arr.shape[ax] IndexError: tuple index out of range
  • 索引需要在 0 到 [数组大小]-1 之间访问。即,如果您需要访问大小为 100 的数组的最后一个元素(例如您的第三个索引),则需要使用 arr[99]。所以,在你的问题中,尝试使用my_data[index1-1][index2-1][index3-1]

标签: python arrays python-3.x numpy mean


【解决方案1】:

只需将np.mean()axis 关键字一起使用:

import numpy as np

np.random.seed(0)

data = np.random.randint(0,5,size=(3,3,3))

产量:

[[[4 0 3]
  [3 3 1]
  [3 2 4]]

 [[0 0 4]
  [2 1 0]
  [1 1 0]]

 [[1 4 3]
  [0 3 0]
  [2 3 0]]]

然后申请:

np.mean(data,axis=1)

#Or data.mean(axis=1)

返回:

[[3.33333333 1.66666667 2.66666667]
 [1.         0.66666667 1.33333333]
 [1.         3.33333333 1.        ]]

【讨论】:

  • 成功了!!!!!!!!!!!!!!!谢谢你:-)
猜你喜欢
  • 1970-01-01
  • 2019-09-22
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2018-12-10
  • 1970-01-01
相关资源
最近更新 更多