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

如何在R中将3列无间隙合并为1列(仅选取指定3列)

解决方法

R 实现

方法1:使用coalesce(推荐)

如果数据表中的空值是NA,直接用dplyr的coalesce函数即可,它支持多列取第一个非空值。注意列名带空格时要用反引号包裹:

library(dplyr)

# 选取目标三列并合并
result_df <- df %>%
  select(Country, `Country 2`, `Country 3`) %>%
  mutate(`Final Country` = coalesce(Country, `Country 2`, `Country 3`)) %>%
  select(`Final Country`)

如果空值是空字符串(""),需要先将其转为NA再使用coalesce:

result_df <- df %>%
  mutate(across(c(Country, `Country 2`, `Country 3`), ~na_if(., ""))) %>%
  select(Country, `Country 2`, `Country 3`) %>%
  mutate(`Final Country` = coalesce(Country, `Country 2`, `Country 3`)) %>%
  select(`Final Country`)

方法2:使用pivot_longer转格式

通过宽表转长表,过滤空值后得到结果:

library(tidyr)
library(dplyr)

result_df <- df %>%
  select(Country, `Country 2`, `Country 3`) %>%
  pivot_longer(
    cols = everything(),
    names_to = NULL,
    values_to = "Final Country"
  ) %>%
  filter(`Final Country` != "") # 空值为NA时改用!is.na(`Final Country`)

Python(Pandas)实现

方法1:使用bfill/ffill

利用每行仅一个非空值的特点,横向填充后取第一列:

import pandas as pd

# 选取目标三列
target_cols = ['Country', 'Country 2', 'Country 3']
selected_df = df[target_cols]

# 横向向后填充,取第一列作为结果
result_df = pd.DataFrame({'Final Country': selected_df.bfill(axis=1).iloc[:, 0]})

方法2:使用stack转格式

stack会自动忽略空值,转成Series后再转为DataFrame:

result_df = df[['Country', 'Country 2', 'Country 3']].stack().reset_index(drop=True).to_frame('Final Country')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:25:07