gpt4 book ai didi

python - 平均忽略 NumPy 数组中列的 NaN,而不使用 numpy.nanmean

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:29 31 4
gpt4 key购买 nike

我有一个如下所示的 numpy 数组:

x = array([[  1.,   2.,   3.],
[ 4., 5., 6.],
[ nan, 8., 9.]])

我想计算每列的平均值。如果我使用 np.mean(x, axis=0) ,然后我得到 nan作为第一列的平均值,并使用 x[~np.isnan(x)]过滤掉nan值将数组展平为一维数组。

我需要使用旧版本的 numpy,所以我无法使用 numpy.nanmean

编辑:This comment解释了为什么这不是发布的问题的重复

最佳答案

一种方法是使用 bool 索引 -

def nanmean_cols(x):
mask = ~np.isnan(x)
x_masked = np.where(mask, x, 0)
return x_masked.sum(0)/mask.sum(0)

示例运行 -

In [114]: x
Out[114]:
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ nan, 8., 9.]])

In [115]: np.nanmean(x,axis=0)
Out[115]: array([ 2.5, 5. , 6. ])

In [117]: nanmean_cols(x)
Out[117]: array([ 2.5, 5. , 6. ])

关于python - 平均忽略 NumPy 数组中列的 NaN,而不使用 numpy.nanmean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44781504/

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