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

如何按指定列分组为Pandas DataFrame添加指定值列?

按ID匹配合并Pandas DataFrame(一对多关联)

你需要的是**左连接(Left Join)**操作,用Pandas的merge()函数就能直接实现,groupby是用于分组聚合的工具,不适合这种关联匹配场景。

代码实现步骤:

  1. 定义对应你提供的示例DataFrame:
import pandas as pd

df_a = pd.DataFrame({
    'ID': [1,1,1,1,2,2,3,3,3],
    'irrelevant_value': [1.2,2.3,0.9,1.1,2.7,3.1,1.3,0.2,2.3]
})

df_b = pd.DataFrame({
    'ID': [1,2,3],
    'add_these_values_to_the_same_ID': [100,120,90]
})
  1. 执行左连接合并:
# 以ID为匹配键,将df_b的内容关联到df_a的对应行
merged_df = df_a.merge(df_b, on='ID', how='left')
print(merged_df)

执行结果:

ID  irrelevant_value  add_these_values_to_the_same_ID
0   1               1.2                              100
1   1               2.3                              100
2   1               0.9                              100
3   1               1.1                              100
4   2               2.7                              120
5   2               3.1                              120
6   3               1.3                               90
7   3               0.2                               90
8   3               2.3                               90

原理说明:

  • on='ID'指定用ID列作为匹配的关联键;
  • how='left'表示保留左表(df_a)的所有行,同时将右表(df_b)中对应ID的值自动填充到每一行,正好实现你需要的一对多关联效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:38:08