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

如何遍历两个同维度Pandas DataFrame的相同索引行列获取对应值

实现思路与代码

你的需求可以通过iterrows()遍历df1的每一行,结合行列索引定位df2对应值来实现,下面是修正后的代码:

import pandas as pd

# 构造示例数据(实际使用替换成你的df1和df2即可)
df1 = pd.DataFrame({
    'column1': ['A', 'B', 'C'],
    'column2': ['D', 'A', 'F'],
    'column3': ['G', 'H', 'A']
})
df2 = pd.DataFrame({
    'column1': ['E', 'I', 'J'],
    'column2': ['K', 'L', 'M'],
    'column3': ['N', 'O', 'P']
})

# 遍历df1的每一行,获取行索引和行数据
for row_idx, row_data in df1.iterrows():
    # 筛选当前行中值为"A"的所有列索引
    matched_columns = row_data[row_data == "A"].index
    # 逐个取出df2对应位置的值
    for col in matched_columns:
        target_value = df2.loc[row_idx, col]
        print(f"df1行{row_idx}列{col}的'A'对应df2的值: {target_value}")

关键说明

  • 你原来的for row in df1是遍历df1的列名,不是行数据,这是核心错误,改用iterrows()才能拿到每一行的索引和完整数据
  • row_data[row_data == "A"].index会找出当前行所有值为"A"的列,支持一行存在多个"A"的情况
  • 因为两个DataFrame维度相同,用df2.loc[row_idx, col]可以精准定位对应单元格;若你的DataFrame用的是纯位置索引(无自定义列名/行名),也可以用df2.iloc[row_idx, df1.columns.get_loc(col)]来定位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:10:46