首页 > 解决方案 > 计算没有for循环的numpy数组部分的平均值

问题描述

我有一个 NumPy 数组:

a.shape: (24, 124, 117, 1)

如果我取两个内部数组的 10 x 10 子集

b = a[:,34:44,100:110,0]

b.shape:

(24, 10, 10)

要获取每个 10 x 10 数组中值的平均值列表:

the_list = []
for i in b:
    the_list.append(np.nanmean(i))

print(the_list)
[1.3890099800025781, 1.4469500441974863, 1.3629133841057566, 1.415756533959169, 1.4254133193054614, 1.5217992758345105, 1.6735920775699795, 1.968677630129286, 2.097451850128511, 2.1386300417406416, 2.536669441756218, 2.3351648894197727, 2.794611866191022, 2.524879009293537, 3.1834270587157953, 4.049452682004729, 3.1542556793742387, 3.498059377421739, 4.439820758482223, 3.446379020262416, 4.8295208426437535, 3.7539767849251833, 5.08349934334655, 4.448043719645083]

for有什么比循环更好的方法来做到这一点?

标签: pythonnumpy

解决方案


np.nanmean(a[:,34:44,100:110,0], axis=(-1, -2)

感谢 Nils 的评论。


推荐阅读