2024-10-01 11:37:37 发布
网友
我有一个1D数组,我想用numpy bincount来创建一个直方图。它工作正常,但我希望它忽略NaN值。
numpy bincount
histogram = np.bincount(distancesArray, weights=intensitiesArray) / np.bincount(distancesArray)
我该怎么做?
谢谢你的帮助!在
整数值数组中不能有NaN。如果您试图拨打np.bincount,它将抱怨:
NaN
np.bincount
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
如果执行强制转换(.astype(int)),则会得到疯狂的值,如-9223372036854775808。可以通过选择非NaN值来克服此问题:
.astype(int)
我认为你的问题是:
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权重:
您可以将其转换为pandas系列并删除空值。在
ds = pd.Series(distancesArray) ds = ds[ds.notnull()] #returns non nullvalues
整数值数组中不能有
NaN
。如果您试图拨打np.bincount
,它将抱怨:如果执行强制转换(
^{pr2}$.astype(int)
),则会得到疯狂的值,如-9223372036854775808。可以通过选择非NaN值来克服此问题:我认为你的问题是:
解决方案只是使用索引来仅保留非nan权重:
^{pr2}$您可以将其转换为pandas系列并删除空值。在
相关问题 更多 >
编程相关推荐