在python中忽略numpybincount中的NaN

2024-10-01 11:37:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我该怎么做?

谢谢你的帮助!在


Tags: numpynp数组nan直方图histogramweightsbincount
3条回答

整数值数组中不能有NaN。如果您试图拨打np.bincount,它将抱怨:

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

如果执行强制转换(.astype(int)),则会得到疯狂的值,如-9223372036854775808。可以通过选择非NaN值来克服此问题:

^{pr2}$

我认为你的问题是:

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权重:

^{pr2}$

您可以将其转换为pandas系列并删除空值。在

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

相关问题 更多 >