python - 线性插值以找到 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 值的坐标。
解决方案
的格式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
推荐阅读
- python - 如何在 nodejs 子进程中使用 python 脚本创建文件?
- python - Python 无法在 windows -EAST 上编译 lanms
- javascript - 计算单选按钮和下拉列表的价格
- amazon-web-services - EB CLI 仅作为 sudo 工作;否则给出'DistributionNotFound'
- c - 使用for循环在C中反转字符串
- xamarin.android - 如何在 Xamarin.android 中单击的项目上从 recyclerview 传递数据
- android - 如何根据xml中的基色值和alpha值设置颜色?
- c# - 如何在 CsvHelper 中以毫秒为单位序列化 DateTime
- c# - 如何动态创建视图 MVC
- java - Apache POI - 如何获取与 Excel 中显示的格式完全相同的日期?