在python中忽略numpy bincount中的NaN
我有一个1D数组,我想使用在python中忽略numpy bincount中的NaN,python,numpy,nan,Python,Numpy,Nan,我有一个1D数组,我想使用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]) # we
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])
整数值数组中不能有
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])
您可以将其转换为一个系列并删除空值
ds = pd.Series(distancesArray)
ds = ds[ds.notnull()] #returns non nullvalues