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

如何在Pandas中根据列索引值匹配获取DataFrame数据?

Pandas按列索引匹配取值实现方案

原始数据

import pandas as pd

df = pd.DataFrame({'A': [0, 0, 2, 2],
                   'B': [1, 1, 1, 2]})

df2 = pd.DataFrame({'X': ['a', 'aa', 'a', 'a', 'a'],
                    'Y': ['b', 'bb', 'b', 'b', 'b'],
                    'Z': ['c', 'c', 'cc', 'c', 'c']})

期望输出

df3 = pd.DataFrame({'A': ['a', 'aa', 'cc', 'c'],
                    'B': ['b', 'bb', 'b', 'c']})

实现代码

直接用apply结合iloc就能完成匹配:

df3 = df.apply(lambda col: df2.iloc[col.index, col.values])

代码说明

  • 遍历df的每一列(A、B列),对列内每个元素做匹配:
    • col.index获取当前列的行号,对应df2中要取值的行位置;
    • col.values是当前列的数值,对应df2的列索引;
    • df2.iloc[行号列表, 列索引列表]会按位置一一匹配,取出对应元素组成新列,最终拼接成目标DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:40:10