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

多表递归匹配数据:请求生成递归关联代码输出多个DataFrame

解决方案

表结构

Table1

A1
D1
B2
A5
C8
B5

Table2

TargetCol SourceCol
A1        E8
B2        C9
E8        F2
C9        D2
F2        A8
D2        E2
C8        G2
G2        K4

需求

从Table1中的A1、B2、C8出发,在Table2中递归匹配关联,生成三个指定的DataFrame。

实现代码(Python + Pandas)

import pandas as pd

# 初始化Table1和Table2数据
table1 = pd.DataFrame({'Col': ['A1', 'D1', 'B2', 'A5', 'C8', 'B5']})
table2 = pd.DataFrame({
    'TargetCol': ['A1', 'B2', 'E8', 'C9', 'F2', 'D2', 'C8', 'G2'],
    'SourceCol': ['E8', 'C9', 'F2', 'D2', 'A8', 'E2', 'G2', 'K4']
})

# 递归追踪关联链条的函数
def get_chain(start_val, mapping_table):
    chain_records = []
    current_val = start_val
    while True:
        # 查找当前值对应的映射记录
        match_row = mapping_table[mapping_table['TargetCol'] == current_val]
        if match_row.empty:
            break
        next_val = match_row.iloc[0]['SourceCol']
        chain_records.append((current_val, next_val))
        current_val = next_val
    return pd.DataFrame(chain_records)

# 生成目标DataFrame
df1 = get_chain('A1', table2)
df2 = get_chain('B2', table2)
df3 = get_chain('C8', table2)

# 输出结果
print("Dataframe1:")
print(df1)
print("\nDataframe2:")
print(df2)
print("\nDataframe3:")
print(df3)

代码说明

  1. 用Pandas构建两个表的DataFrame结构;
  2. get_chain函数接收起始值和映射表,循环查找当前值在TargetCol中的匹配项,取出对应的SourceCol作为下一个追踪值,直到无匹配项为止;
  3. 分别传入A1、B2、C8三个起始值,生成对应的关联链条DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:10:11