You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas中基于区间位置高效计算近似值的实现方法

实现方法

推荐使用pandas原生的重索引+线性插值功能,全程矢量化运算,无需自定义循环逻辑,效率极高,代码实现如下:

完整代码示例

import pandas as pd

# 构建示例参考数据
d = {'col1': [1, 5, 10, 22, 36, 57], 'col2': [100, 450, 1200, 2050, 3300, 6000]}
df = pd.DataFrame(data=d)

# 构建待处理数据
d2 = {'col2': [100, 200, 450, 560, 900, 1200, 1450, 1800, 2050, 2600, 3300, 5000, 6000]}
df2 = pd.DataFrame(data=d2)

# 核心处理逻辑
# 1. 参考数据按col2排序后设置为索引(插值要求索引有序)
df_ref = df.sort_values('col2').set_index('col2')
# 2. 重索引到待处理的col2取值,执行线性插值
df2['col1'] = df_ref['col1'].reindex(df2['col2']).interpolate(method='linear').values

结果验证

运行后df2的col1列输出完全符合规则要求,示例数值验证:

  • 完全匹配的col2=100对应col1=1.0,col2=450对应col1=5.0
  • 未匹配的col2=200对应col1≈2.142857,和题目给出的计算结果一致

可选拓展

如果待处理的col2取值存在超出参考数据col2上下限的情况,可以在interpolate方法中添加limit_direction='both'参数,自动用边界值填充空缺。

内容的提问来源于stack exchange,提问作者Gal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:03:03