python - 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 中的什么功能?
解决方案
您描述的函数可以被认为是在适当大小的单位矩阵的行(或列)之间进行插值: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. ])
推荐阅读
- python-3.x - 如何在 ubuntu 18.04 上安装 ansible 2.9+ 并使用 python3?
- wordpress - 如何在 WordPress 中重新创建用户表?
- worhp - WORHP 在局部仿射函数上非常慢
- android - WebView 无法访问 android_res 但 android_asset 工作
- django - 为什么 save() 方法在 django 模型中有另一个带有 super 的 save() 方法
- python - 是否可以在 R 中开发或创建类似 python 的类?
- angular - 如何在不导入所有角度组件 SCSS 文件的情况下引用 SASS 函数
- javascript - Lodash递归函数超过最大堆栈大小
- c# - 在 C# 中获取 .csv 文件中的特定行和列值
- mysql - Mysql存储过程在循环内插入查询仅插入最后一个值