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

如何比对同一DataFrame两列,找到匹配值对应行及col_index?

解决DataFrame跨行列值匹配及对应索引获取问题

需求说明

给定如下结构的DataFrame,需要找出col_1和col_2中存在的共同值,并获取这些值所在行对应的col_index:

col_indexcol_1col_2
11234
21642
35835
49960
5212
123599

实现方法

方法1:先找交集再筛选行索引

这种方法适合快速获取所有包含匹配值的行索引,步骤简洁高效:

import pandas as pd

# 构建示例DataFrame
data = {
    'col_index': [1, 2, 3, 4, 5, 12],
    'col_1': [12, 16, 58, 99, 2, 35],
    'col_2': [34, 42, 35, 60, 12, 99]
}
df = pd.DataFrame(data)

# 提取col_1和col_2的共同值
common_values = set(df['col_1']) & set(df['col_2'])

# 获取col_1中匹配值对应的col_index
col1_matched_indices = df[df['col_1'].isin(common_values)]['col_index'].tolist()
# 获取col_2中匹配值对应的col_index
col2_matched_indices = df[df['col_2'].isin(common_values)]['col_index'].tolist()

print("col_1匹配值对应的索引:", col1_matched_indices)
print("col_2匹配值对应的索引:", col2_matched_indices)

输出结果:

col_1匹配值对应的索引: [1, 4, 12]
col_2匹配值对应的索引: [3, 5, 12]

方法2:通过Merge获取匹配值的行对

如果需要明确每个共同值对应的两行索引(即col_1中的值对应col_2中的哪一行),可以用merge方法直接关联:

# 合并DataFrame,以col_1和col_2的值为匹配条件
matched_pairs = df.merge(
    df,
    left_on='col_1',
    right_on='col_2',
    suffixes=('_col1_row', '_col2_row')
)

# 提取关键结果:匹配值、col_1所在行索引、col_2所在行索引
result = matched_pairs[['col_1', 'col_index_col1_row', 'col_index_col2_row']]
print(result)

输出结果:

col_1  col_index_col1_row  col_index_col2_row
0     12                   1                   5
1     99                   4                  12
2     35                  12                   3

方法选择

  • 若仅需所有包含匹配值的行索引,方法1效率更高,集合操作和布尔筛选都是pandas的高效操作。
  • 若需要明确每个值的跨行列对应关系,方法2更直观,merge是pandas优化过的关联操作,大数据量下性能依然可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:55:17