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

使用to_list生成第二个DataFrame后合并两个Pandas DataFrame数据

解决方法

要实现两个DataFrame的关联,核心是给upcoming_events_df补充对应的Comp_ID字段,再通过这个共同字段和football_league_df合并。具体步骤如下:

1. 从API返回的事件数据中提取Comp_ID

Betfair的list_events返回的每个Event对象包含competition属性(记录该赛事所属的联赛ID和名称),我们可以直接从中提取Comp_ID,再生成带该字段的upcoming_events_df:

import pandas as pd

# 遍历API返回的event对象,提取Event Name、Event_ID和对应的Comp_ID
event_records = []
for event in upcoming_events:
    event_records.append({
        "Event Name": event.name,
        "Event_ID": event.id,
        "Comp_ID": event.competition.id  # 提取赛事所属联赛的ID
    })

# 转换为DataFrame
upcoming_events_df = pd.DataFrame(event_records)

2. 合并两个DataFrame

利用pandas.merge()方法,通过Comp_ID字段将两个DataFrame关联,补充Competition列:

# 合并DataFrame,保留upcoming_events_df的所有列,关联对应的联赛名称
combined_df = pd.merge(
    upcoming_events_df,
    football_league_df[["Comp_ID", "Competition"]],  # 只取需要关联的列
    on="Comp_ID",
    how="left"  # 保留所有赛事记录,即使出现未匹配的情况(这里因过滤条件,理论上都能匹配)
)

最终效果

合并后的combined_df结构示例:

Event NameEvent_IDComp_IDCompetition
CFR Cluj v ACS Sepsi OSK3180592612200889English Northern Premier League
Neuchatel Xamax v Schaffhausen3182640112199359Northern Irish Premiership

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:10:59