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

如何在Pandas DataFrame中新增列记录每行包含NaN的列名

你可以使用 pandas 的 apply 逐行遍历完成需求,核心逻辑是对每行判断空值,提取对应空值的列名转为列表:

完整实现代码

import pandas as pd
import numpy as np

# 构造示例DataFrame
df = pd.DataFrame({
    'ID': [0, 1, 2, 3],
    'Y1': [np.nan, np.nan, np.nan, 5],
    'Y2': [8, np.nan, np.nan, 3],
    'Y3': [4, 1, np.nan, 7]
})

# 筛选需要判断空值的列(排除ID列)
check_cols = ['Y1', 'Y2', 'Y3']

# 新增Result列存储空值列名列表
df['Result'] = df[check_cols].apply(lambda row: row.index[row.isna()].tolist(), axis=1)

print(df)

输出结果

ID   Y1   Y2   Y3          Result
0   0  NaN  8.0  4.0            [Y1]
1   1  NaN  NaN  1.0       [Y1, Y2]
2   2  NaN  NaN  NaN  [Y1, Y2, Y3]
3   3  5.0  3.0  7.0              []

如果需要列表元素显式为带引号的字符串格式,可以在生成时加astype(str)调整即可。

内容的提问来源于stack exchange,提问作者vinicius de castro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:36:04