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

Python如何获取两个DataFrame中site_no列值相同的对应行索引

匹配两个DataFrame同值字段的行索引对方案

原有代码问题

你的代码仅对ucol_gages做单向步进匹配,要求两个DataFrame的site_no严格按顺序一一对应才能正确匹配,不符合遍历所有行组合找全匹配对的需求,因此会出现漏匹配的情况。

推荐极简实现方案

优先使用pandas内置的merge方法,底层做了性能优化,比自行编写循环效率高很多,能覆盖所有值匹配的组合,代码如下:

# 为两个DataFrame新增保留原始索引的字段
ucol_gages = ucol_gages.reset_index(names='ucol_index')
current_gages = current_gages.reset_index(names='current_index')

# 按site_no做内连接,仅保留两边都匹配的记录
matched_pairs = ucol_gages[['ucol_index', 'site_no']].merge(
    current_gages[['current_index', 'site_no']],
    on='site_no'
)

# 转换为[ucol索引, current索引]格式的列表
gages_idx = matched_pairs[['ucol_index', 'current_index']].values.tolist()

循环实现方案(仅用于理解逻辑,不推荐大数据量使用)

如果你需要自行通过循环实现全组合匹配,需要用双层循环遍历两个DataFrame的所有行组合:

gages_idx = []
for u_idx, u_row in ucol_gages.iterrows():
    for c_idx, c_row in current_gages.iterrows():
        if u_row['site_no'] == c_row['site_no']:
            gages_idx.append([u_idx, c_idx])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:15:06