首页 > 解决方案 > numpy : 要插入的浮点索引

问题描述

我想做的是如下:

我有一个最初为零的向量 A

[0,0,0]

我得到了一个浮动索引

0.5

我所说的用浮点索引插值的意思是一个将有这样的输出的函数

[0.5,0.5,0]

再举几个例子

1 -> [0,1,0]
2 -> [0,0,1]
1.5 -> [0,0.5,0.5]
1.9 -> [0,0.1,0.9]

这是如何调用的以及我上面描述的行为在 numpy 中的什么功能?

标签: pythonnumpy

解决方案


您描述的函数可以被认为是在适当大小的单位矩阵的行(或列)之间进行插值:0给出第一个基向量[1, 0, 0]的输入,1给出的输入[0, 1, 0]等等,非整数输入之间插值两个最近的向量。

NumPy 的interp函数不支持向量之间的插值,但 SciPy 的interp1d函数可以,并为您提供所需的内容。这是一个演示:

>>> from scipy.interpolate import interp1d
>>> import numpy as np
>>> interpolator = interp1d(np.arange(3), np.identity(3))
>>> interpolator(0.5)
array([0.5, 0.5, 0. ])
>>> interpolator(1)
array([0., 1., 0.])
>>> interpolator(2)
array([0., 0., 1.])
>>> interpolator(1.5)
array([0. , 0.5, 0.5])
>>> interpolator(1.9)
array([0. , 0.1, 0.9])

你没有说你想要外推的行为。也就是说,对于小于0.0或大于的输入2.0。但是 SciPy 在这里也为您提供了各种选择。默认情况下,它会引发异常:

>>> interpolator(-0.2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/interpolate/polyint.py", line 78, in __call__
    y = self._evaluate(x)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/interpolate/interpolate.py", line 677, in _evaluate
    below_bounds, above_bounds = self._check_bounds(x_new)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/interpolate/interpolate.py", line 706, in _check_bounds
    raise ValueError("A value in x_new is below the interpolation "
ValueError: A value in x_new is below the interpolation range.

但您也可以推断或提供填充值。这是一个外推示例:

>>> interpolator = interp1d(np.arange(3), np.identity(3), fill_value="extrapolate")
>>> interpolator(-0.2)
array([ 1.2, -0.2,  0. ])

推荐阅读