gpt4 book ai didi

python - 在 python 中忽略 numpy bincount 中的 NaN

转载 作者:太空狗 更新时间:2023-10-30 00:55:49 24 4
gpt4 key购买 nike

我有一个一维数组,我想使用 numpy bincount 创建直方图。它工作正常,但我希望它忽略 NaN 值。

histogram = np.bincount(distancesArray, weights=intensitiesArray) / np.bincount(distancesArray)

我该怎么做?

感谢您的帮助!

最佳答案

我认为您的问题是:

import numpy

w = numpy.array([0.3, float("nan"), 0.2, 0.7, 1., -0.6]) # weights
x = numpy.array([0, 1, 1, 2, 2, 2])
numpy.bincount(x, weights=w)
#>>> array([ 0.3, nan, 1.1])

解决方案就是使用索引只保留非 nan 权重:

keep = ~numpy.isnan(w)
numpy.bincount(x[keep], weights=w[keep])
#>>> array([ 0.3, 0.2, 1.1])

关于python - 在 python 中忽略 numpy bincount 中的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219745/

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