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

求助:如何基于日期与ID关联条件为DataFrame添加搭档列

为Pandas DataFrame匹配搭档组合并新增列的解决方案

问题说明

现有两个Pandas DataFrame:

  • df1 存储各ID的日期、工时数据
  • df2 存储特定日期的搭档组合关系

数据示例

import pandas as pd
# 注:原代码中df2的Dataframe拼写错误,已修正为DataFrame
df1 = pd.DataFrame({'ID': ['Polar', 'Dex', 'Nikita', 'Lunar', 'Astro', 'Pin', 'Polar'], 
                   'Date': ['01-03-2023', '01-03-2023', '02-03-2023', '03-03-2023', '04-03-2023', '04-03-2023', '05-03-2023'], 
                   'Hours': ['5', '8', '9', '11', '12', '2', '6']})
df2 = pd.DataFrame({'Couple': ['Polar-Dex', 'Astro-Pin'], 
                   'Date': ['01-03-2023', '04-03-2023']})

需求目标

为df1新增Couple列:

  • 当ID在对应日期的df2搭档组合中时,填入组合名
  • 无匹配项时,填入自身ID

解决方案

通过拆分df2的组合列,构建ID-日期-组合名的映射关系,再与df1合并实现需求,具体步骤如下:

1. 拆分并展开df2的组合数据

将df2中的Couple按-拆分,生成每个ID对应的日期和组合名:

# 拆分Couple列,生成包含单个ID的临时行
df2_expanded = df2.assign(ID=df2['Couple'].str.split('-')).explode('ID')

2. 合并数据并填充空值

以Date和ID为关联键,将df1与展开后的df2左连接,再把空值替换为自身ID:

# 左连接保留df1所有数据
result = df1.merge(df2_expanded[['Date', 'ID', 'Couple']], on=['Date', 'ID'], how='left')
# 填充无匹配的项为自身ID
result['Couple'] = result['Couple'].fillna(result['ID'])

最终结果

执行后result的输出如下:

IDDateHoursCouple
Polar01-03-20235Polar-Dex
Dex01-03-20238Polar-Dex
Nikita02-03-20239Nikita
Lunar03-03-202311Lunar
Astro04-03-202312Astro-Pin
Pin04-03-20232Astro-Pin
Polar05-03-20236Polar

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:45:23