假设我有以下 pandas DataFrame
>>> df = pd.DataFrame([[-10, -5, 0, 10], [17, 10, 16, 20], [40, 30, 10, -6]], columns=[0, 10, 20, 30])
>>> df.values
array([[-10, -5, 0, 10],
[ 17, 10, 16, 20],
[ 40, 30, 10, -6]])
>>> df.columns
Int64Index([0, 10, 20, 30], dtype='int64')
其中列名是我要插值的 x 数组,表中的值是 y 值。我想对每一行执行线性插值,每行有一个 new_x,即 where
new_x = [5, 15, 25]
我想使用列名作为 x 值,第一行作为 y 值来插入值
5
,依此类推具有预期结果的行 [-7.5, 13., 2.]
我试过下面的
from scipy import interpolate
interpolate.interp1d(x=df.columns,y=df)(new_x)
但这给了
array([[-7.5, -2.5, 5. ],
[13.5, 13. , 18. ],
[35. , 20. , 2. ]])
这是在每行中插入 new_x 的每个元素。相反,我只想要那个结果的对角线。
我可以通过在每一行上应用一个插值函数来做到这一点,但是我缺少更自然/更快的单行方式吗?
This question问类似的东西,但只是在2点之间进行插值。
diag
获得输出的对角线:
import numpy as np
out = np.diag(interpolate.interp1d(x=df.columns,y=df)(new_x))
输出:
array([-7.5, 13. , 2. ])