python - 值错误: can only convert an array of size 1 to a Python scalar for Numpy Select

标签 python arrays numpy

newXbreaks 分别是形状为 (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/

相关文章:

python - 如何在numpy中反转子数组?

python - 如何在 Python 中 append 分页响应的数据集?

Python最快访问大文件中的第n行

python - 如何从 git 调用实用程序 omeld (oitnb)

python - 制作类似于 MATLAB 的 Python 2D 掩码数组

java - 如何在 Java 中循环遍历 2D ArrayList 并填充它?

python - 如何在 Pandas 中有条件地交换列

javascript - 使用 date-fns 的 max 函数从日期字符串数组中查找最大日期

python - 将 numpy 数组的切片替换为另一个数组中的值

python - PyArray_SimpleNewFromData