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

如何使用pandas合并两个形状不同的数据集

不同大小数据集按公共键合并方案

使用Python的Pandas库的左连接功能即可实现你需要的一对多匹配填充效果,操作步骤如下:

完整实现代码

1. 导入依赖并构造原始数据集

import pandas as pd

# 长表:包含多条相同identifier的收入数据
df = pd.DataFrame({
    'identifier': [1,1,1,2,2,2],
    'Income': [50,40,70,50,60,30],
})

# 短表:每个identifier对应唯一的租金数据
df2 = pd.DataFrame({
    'identifier': [1,2],
    'Rent': [150,300],
})

2. 执行合并操作

使用merge方法指定公共关联键和左连接模式即可:

# on参数指定关联的公共键,how='left'表示以左表df的所有行为基准做匹配
df3 = df.merge(df2, on='identifier', how='left')

3. 结果验证

将合并后的DataFrame转为列表格式的字典即可得到你示例中的输出:

print(df3.to_dict('list'))

输出结果和你预期的df3完全一致:

{'identifier': [1, 1, 1, 2, 2, 2], 'Income': [50, 40, 70, 50, 60, 30], 'Rent': [150, 150, 150, 300, 300, 300]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:09:04