在Python中忽略numpy bincount中的NaN

5 投票
3 回答
4289 浏览
提问于 2025-04-18 09:47

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

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

我该怎么做呢?

谢谢你的帮助!

3 个回答

0

你可以把它转换成一个pandas的序列,然后去掉里面的空值。

ds = pd.Series(distancesArray)
ds = ds[ds.notnull()]   #returns non nullvalues
2

在一个只存整数的数组里,你不能有NaN(不是一个数字)。如果你试着使用np.bincount这个函数,它会报错。

TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'

如果你强行把数据转换成整数(用.astype(int)),你会得到一些奇怪的值,比如 -9223372036854775808。要解决这个问题,你可以选择那些不是NaN的值:

mask = ~np.logical_or(np.isnan(distancesArray), np.isnan(intensitiesArray))
histogram = np.bincount(distancesArray[mask].astype(int), 
                        weights=intensitiesArray[mask])
7

我觉得你的问题是这样的:

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])

撰写回答