如何简洁实现pandas DataFrame索引匹配及插值外推?
简洁实现索引匹配+插值/外推
先假设你的示例数据如下:
import pandas as pd # 目标索引的DataFrame df1 = pd.DataFrame({'value1': [0, 0, 0, 0]}, index=[0.2, 0.5, 1.0, 1.5]) # 需要调整索引的DataFrame df2 = pd.DataFrame({'value2': [1.0, 2.0, 3.0]}, index=[0.5, 1.0, 1.5])
一步完成索引对齐+线性插值与外推
用reindex结合interpolate就能简洁实现需求,无需拆分繁琐步骤:
# 对齐索引并完成线性插值+外推 df2_aligned = df2.reindex(df1.index).interpolate(method='linear', limit_direction='both')
运行后得到的结果完全符合你的要求:
| index | value2 |
|---|---|
| 0.2 | 0.8 |
| 0.5 | 1.0 |
| 1.0 | 2.0 |
| 1.5 | 3.0 |
参数说明
reindex(df1.index):将df2的索引调整为与df1一致,缺失位置自动填充NaNinterpolate(method='linear', limit_direction='both'):method='linear':采用线性插值逻辑limit_direction='both':允许向索引的前后两端做外推(默认仅支持内部插值)
如果你的pandas版本在1.3.0及以上,也可以用extrapolate=True替代limit_direction='both',效果完全一致:
df2_aligned = df2.reindex(df1.index).interpolate(method='linear', extrapolate=True)
其他外推选项
如果需要非线外推,比如用最近值填充,只需把method换成nearest并保留limit_direction='both'即可,线性外推是最贴合你示例场景的方案。
内容的提问来源于stack exchange,提问作者Grismar
相关产品推荐
相关产品推荐

