首页 > 解决方案 > 线性插值以找到 y 值

问题描述

我有一个数据框:

1  Amazon        1      x  0.0     1.0     2.0    3.0    4.0
2  Amazon        1      y  0.0     0.4     0.8    1.2    1.6
4  Amazon        2      x  0.0     2.0     4.0    6.0    8.0
5  Amazon        2      y  0.0     1.0     2.0    3.0    4.0

df2:

 Amazon   1       1
 Amazon   2       2.3
 Netflix  1       4.1
 Netflix  2       5.5

鉴于这两个数据帧,我试图使用线性插值来找到 df2 的“y 值”,使用 df1 断点

预期输出:

   Amazon   1       1    ...
   Amazon   2       2.3  ...

线性插值的公式为:y = y1 + ((x – x1) / (x2 – x1)) * (y2 – y1),其中 x 为已知值,y 为未知值,x1 和 y1 为坐标低于已知 x 值,x2 和 y2 是高于 x 值的坐标。

标签: pythonpandasdataframenumpylinear-interpolation

解决方案


的格式df似乎很奇怪(列中的数据点,而不是行)。

以下根本不是最干净的解决方案:

import numpy as np

lookup_df = df1.set_index(["Name", "Segment", "Axis"]).T

def find_interp(row):
    try:
        res = np.interp([row["x"]], lookup_df[(row["Name"], row["Segment"], "x")], lookup_df[(row["Name"], row["Segment"], "y")])
    except:
        res = [np.nan]
    return res[0]


>>> df2["y"] = df2.apply(find_interp, axis=1)
>>> df2
      Name  Segment    x     y
0   Amazon        1  1.0  0.40
1   Amazon        2  2.3  1.15
2  Netflix        1  4.1   NaN
3  Netflix        2  5.5   NaN

推荐阅读