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

如何根据第一个DataFrame的索引值匹配添加第二个DataFrame的weighting_factor值

实现方案

你可以通过pandas的IntervalIndex实现区间匹配,该方案天然适配后续两个DataFrame同步扩展的场景,不需要修改核心逻辑。

核心实现代码

import pandas as pd

# ---------------------- 示例数据构造 ----------------------
# 第一个待填充的DataFrame
df1 = pd.DataFrame({
    "base_rate": [None, 1.792750, 1.792944],
    "weighting_factor": [None, None, None]
})

# 第二个存储区间与权重映射的DataFrame
df2 = pd.DataFrame({
    "min_index": [0, 9, 18, 27],
    "max_index": [8, 17, 26, 35],
    "weighting_factor": [0.15, 0.20, 0.60, 0.80]
})
# --------------------------------------------------------

# 1. 构造区间-权重映射:closed='both'表示区间包含左右两端的端点
interval_index = pd.IntervalIndex.from_arrays(df2["min_index"], df2["max_index"], closed="both")
weight_map = pd.Series(df2["weighting_factor"].values, index=interval_index)

# 2. 用df1的索引匹配对应区间,填充权重列
df1["weighting_factor"] = df1.index.map(lambda idx: weight_map[weight_map.index.contains(idx)].iloc[0])

扩展适配说明

当df1长度增加、df2同步新增区间段时,只需要重新执行上述两个核心步骤即可完成新数据的填充,不需要调整逻辑。如果是动态更新场景,可将核心逻辑封装为函数,每次df2更新后重新生成weight_map即可。

输出验证

处理后的df1结果如下,符合需求预期:

base_rate  weighting_factor
0        NaN              0.15
1   1.792750              0.15
2   1.792944              0.15

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:39:00