3D numpy数组计算列的平均值与nans

0kjbasz6  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个3D数组:

import numpy as np
import numpy.ma as ma

a = np.array([[[1,2,3],[4,np.nan,6], [7,8,9]],
             [[11,12,13],[14,np.nan,16], [17,18,19]]])

a.shape
(2, 3, 3)

array([[[ 1.,  2.,  3.],
        [ 4., nan,  6.],
        [ 7.,  8.,  9.]],

       [[11., 12., 13.],
        [14., nan, 16.],
        [17., 18., 19.]]])

字符串
所以,我有两组2d数据。我想计算每组的列平均值,并用该值替换nans。
所以,我想要结果:

array([[[ 1.,  2.,  3.],
        [ 4.,  5,   6.],
        [ 7.,  8.,  9.]],

       [[11., 12., 13.],
        [14., 15,  16.],
        [17., 18., 19.]]])

( 2 + 8 = 10 / 2 = 5)

( 12 + 18 = 30 / 2 = 15)


我试探着:

a = np.where(np.isnan(a), 
             ma.array(a, mask=np.isnan(a)).mean(axis=1), 
             a)


沿沿着轴1的平均值,但它给出:

operands could not be broadcast together with shapes (2,3,3) (2,3) (2,3,3)

gj3fmq9x

gj3fmq9x1#

你不能只计算沿第二个轴(轴=1)的平均值沿着,而忽略NaN使用np.**nanmean**,然后将其广播回原始数组形状:

import numpy as np

a = np.array([[[1, 2, 3], [4, np.nan, 6], [7, 8, 9]],
             [[11, 12, 13], [14, np.nan, 16], [17, 18, 19]]])

means = np.nanmean(a, axis=1)
means_reshaped = means[:, np.newaxis, :]
a = np.where(np.isnan(a), means_reshaped, a)

print(a)

字符串

输出:

array([[[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.]],

       [[11., 12., 13.],
        [14., 15., 16.],
        [17., 18., 19.]]])

相关问题