newX
和 breaks
分别是形状为 (24000L,) 和 (7L,) 的 numpy ndarray。 newX 在 (0,9) 范围内。 yvals
是一个基于分割为 10000 (nsegs) 个样本的查找表,称为 xvals
(此处未使用)。
deltaX=(breaks[-1]-breaks[0])/nsegs
xvals=[x+i*deltaX for i in range(nsegs+1)]
break 和 yval 都是单调递增的。基本上,我希望当newX值小于breaks[0]时返回yvals[0],当newX值高于breaks[-1]时返回yvals[-1]。对于其他值,我希望它为 yvals 生成对应于最接近 xval 的点的索引(示例如下所示) 当我执行以下操作时:
condlist=[newX<=breaks[0] , newX < breaks[-1] , newX >= breaks[-1]]
choicelist=[yvals[0] , yvals[((newX-breaks[0]))/deltax.astype(int).item()] , yvals[-1]]
ans = np.select(condlist,choicelist)
我在选择列表行中收到错误 -
ValueError: can only convert an array of size 1 to a Python scalar
我该如何解决这个问题?
最佳答案
这里不需要numpy.select,你的目标可以简单说明
choicelist = yVals[ix]
其中 ix 是要计算的索引数组。我看到的是 newX 被线性转换,四舍五入为整数,并修剪,以便索引不会超出范围 0...len(yVals)-1。这一切都用
来表达ix = np.clip(np.around((newX-breaks[0])/deltax).astype(int), 0, len(yVals)-1)
哪里
np.around((newX-breaks[0])/deltax)
将计算结果舍入为最接近的整数。如果没有舍入,.astype(int) 就会将其取整,这是不太理想的。np.clip(..., 0, len(yVals)-1)
剪辑结果,以便所有索引都有效。
关于python - 值错误: can only convert an array of size 1 to a Python scalar for Numpy Select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732296/