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

问询:将多列binary变量合并为单列的高效实现方法

多列二元教育数据合并为单列的高效方案

针对你这种每行仅存在一个有效学历值(其余为-1)的宽格式数据,以下是不同工具下的高效合并方案:

Python (Pandas)

方法1:替换空值后按行提取

import pandas as pd

# 示例数据
df = pd.DataFrame({
    'ID': [1, 2, 3, 4],
    'high school': ['high school', '-1', '-1', 'high school'],
    'college': ['-1', 'college', '-1', '-1'],
    'PhD': ['-1', '-1', 'PhD', '-1']
})

# 将-1替换为缺失值,按行向前填充后取第一列
df['教育背景'] = df.filter(items=['high school', 'college', 'PhD'])\
                .replace('-1', pd.NA)\
                .bfill(axis=1)\
                .iloc[:, 0]

# 保留需要的列
result = df[['ID', '教育背景']]

方法2:利用Stack重塑数据

# 将ID设为索引,堆叠非缺失值后提取
df['教育背景'] = df.set_index('ID')\
                .replace('-1', pd.NA)\
                .stack()\
                .reset_index(level=1, drop=True)

result = df[['ID', '教育背景']]

R 语言

方法1:使用coalesce提取首个有效值

library(tidyverse)

# 示例数据
df <- tibble(
  ID = c(1, 2, 3, 4),
  `high school` = c("high school", "-1", "-1", "high school"),
  college = c("-1", "college", "-1", "-1"),
  PhD = c("-1", "-1", "PhD", "-1")
)

# 生成教育背景列
df <- df %>%
  mutate(教育背景 = coalesce(
    case_when(`high school` != "-1" ~ `high school`),
    case_when(college != "-1" ~ college),
    case_when(PhD != "-1" ~ PhD)
  )) %>%
  select(ID, 教育背景)

方法2:宽表转长表后过滤

df <- df %>%
  pivot_longer(cols = -ID, names_to = NULL, values_to = "教育背景") %>%
  filter(教育背景 != "-1") %>%
  arrange(ID)

Excel

方法1:IF嵌套函数

假设ID在A列,学历列从B到D,在E2单元格输入:

=IF(B2<>"-1",B2,IF(C2<>"-1",C2,D2))

下拉填充即可。

方法2:TEXTJOIN数组公式

在E2单元格输入(旧版Excel需按Ctrl+Shift+Enter确认,新版直接回车):

=TEXTJOIN("",TRUE,IF(B2:D2<>"-1",B2:D2,""))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:30:57