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

如何在Python/R中合并键列形式不同的两个关联数据集?

Python与R实现数据集合并方案

数据集说明

数据集a

have lunchhave dinner
set aset 1
set bset 2
......

数据集b

variablevariable_valuevalue
have lunchset a0.2
have lunchset b0.5
have dinnerset 11.5
have dinnerset 21.7
.........

目标数据集c

have lunchhave lunch valuehave dinnerhave dinner value
set a0.2set 11.5
set b0.5set 21.7
............

R语言实现方案

你提出的思路需要微调,直接pivot_wider后无法直接与数据集a匹配,正确的做法是拆分数据集b后分别关联:

library(tidyverse)

# 拆分数据集b为午餐、晚餐两个子数据集,并重命名列
lunch_data <- b %>%
  filter(variable == "have lunch") %>%
  rename("have lunch" = variable_value, "have lunch value" = value) %>%
  select(-variable)

dinner_data <- b %>%
  filter(variable == "have dinner") %>%
  rename("have dinner" = variable_value, "have dinner value" = value) %>%
  select(-variable)

# 依次与数据集a合并,得到目标结果
result_c <- a %>%
  left_join(lunch_data, by = "have lunch") %>%
  left_join(dinner_data, by = "have dinner")

Python语言实现方案

使用pandas库可以轻松实现,以下是两种可行方式:

方式一:拆分后逐个合并(直观清晰)

import pandas as pd

# 拆分数据集b为午餐、晚餐子数据集,调整列名
lunch_df = b[b['variable'] == 'have lunch'].rename(
    columns={'variable_value': 'have lunch', 'value': 'have lunch value'}
).drop(columns='variable')

dinner_df = b[b['variable'] == 'have dinner'].rename(
    columns={'variable_value': 'have dinner', 'value': 'have dinner value'}
).drop(columns='variable')

# 逐步合并得到结果
result_c = pd.merge(a, lunch_df, on='have lunch', how='left')
result_c = pd.merge(result_c, dinner_df, on='have dinner', how='left')

方式二:通用化合并(适用于变量较多的场景)

import pandas as pd

# 将数据集b转换为宽格式,自动生成带"value"后缀的列名
b_wide = b.pivot(
    index='variable_value',
    columns='variable',
    values='value'
).reset_index().rename(columns=lambda x: f"{x} value" if x != 'variable_value' else x)

# 循环完成所有变量的合并
result_c = a.copy()
for col in a.columns:
    temp_df = b_wide[['variable_value', f"{col} value"]].rename(columns={'variable_value': col})
    result_c = pd.merge(result_c, temp_df, on=col, how='left')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:40:03