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

如何新增Missing列标识数据表中其他列的NA缺失值?

实现方法

Python(Pandas)方案

直接通过逐行遍历筛选出含NA的列名,拼接成字符串作为新列值:

import pandas as pd
import numpy as np

# 构建原始数据集
df = pd.DataFrame({
    "id": [4, 5, 3, 2],
    "color": ["red", np.nan, "blue", "green"],
    "shape": [np.nan, "square", np.nan, "circle"],
    "animal": [np.nan, "dog", "cat", np.nan]
})

# 生成Missing列:筛选除id外的NA列名并拼接
df["Missing"] = df.apply(
    lambda row: ", ".join(col for col in df.columns if pd.isna(row[col]) and col != "id"),
    axis=1
)

print(df)

运行后输出的结果就和预期一致,逻辑是对每一行检查非id列的NA值,收集对应列名后用逗号分隔。

R语言方案

借助dplyr包的逐行处理能力实现:

library(dplyr)

# 构建原始数据集
df <- data.frame(
  id = c(4, 5, 3, 2),
  color = c("red", NA, "blue", "green"),
  shape = c(NA, "square", NA, "circle"),
  animal = c(NA, "dog", "cat", NA),
  stringsAsFactors = FALSE
)

# 生成Missing列
df <- df %>%
  rowwise() %>%
  mutate(Missing = paste(names(.)[which(is.na(c_across(-id)))], collapse = ", ")) %>%
  ungroup()

print(df)

这里用rowwise()开启逐行模式,c_across(-id)排除id列后检查NA,提取对应列名并拼接成字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:27:42