如何在Pandas中实现一对多连接?附数据表示例
Pandas 实现一对多数据表合并(基于指定连接键)
数据结构说明
df_1 结构
| job_function | job_area | title |
|---|---|---|
| General Management | Human Resources | manager |
| Learning / Training | IT / Computers / Electronics | personnel |
df_2 结构
| job_function | job_area | id | title |
|---|---|---|---|
| General Management | Human Resources | 12312312 | manager |
| Learning / Training | IT / Computers / Electronics | 12312237 | personnel |
| General Management | Human Resources | 12312315 | manager |
| Learning / Training | IT / Computers / Electronics | 12312234 | personnel |
合并实现代码
使用Pandas的merge()方法,指定job_function、job_area、title作为连接键,可自动处理一对多的匹配关系:
import pandas as pd # 构造示例数据 df_1 = pd.DataFrame({ 'job_function': ['General Management', 'Learning / Training'], 'job_area': ['Human Resources', 'IT / Computers / Electronics'], 'title': ['manager', 'personnel'] }) df_2 = pd.DataFrame({ 'job_function': ['General Management', 'Learning / Training', 'General Management', 'Learning / Training'], 'job_area': ['Human Resources', 'IT / Computers / Electronics', 'Human Resources', 'IT / Computers / Electronics'], 'id': ['12312312', '12312237', '12312315', '12312234'], 'title': ['manager', 'personnel', 'manager', 'personnel'] }) # 执行一对多合并 merged_df = pd.merge(df_1, df_2, on=['job_function', 'job_area', 'title'], how='left') print(merged_df)
合并结果说明
运行后会得到如下结果,df_1的每条记录会匹配df_2中所有对应连接键的id:
| job_function | job_area | title | id |
|---|---|---|---|
| General Management | Human Resources | manager | 12312312 |
| General Management | Human Resources | manager | 12312315 |
| Learning / Training | IT / Computers / Electronics | personnel | 12312237 |
| Learning / Training | IT / Computers / Electronics | personnel | 12312234 |
参数说明
on:指定用于匹配的连接键列表,需确保两张表的键名一致how='left':保留df_1的所有行,即使df_2中无对应匹配;若仅需两张表共有的记录,可改为how='inner'
内容的提问来源于stack exchange,提问作者Rus Zzzeta
相关产品推荐
相关产品推荐

