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

如何获取Python DataFrame中空值所在行对应的列名

包含输入文件与输出示例的图片

实现方法

你可以通过pandas内置的空值判断+行维度聚合快速实现需求,以下是两种常用的落地方式:

方法1:逐行遍历实现(可读性高,适合中小数据集)

先判断每个单元格是否为空,再逐行收集空值对应的列名,代码如下:

import pandas as pd
import numpy as np

# 构造测试数据,可替换为自己的DataFrame
df = pd.DataFrame({
    'col1': [1, np.nan, 5, 7, np.nan],
    'col2': [2, 3, np.nan, 8, 9],
    'col3': [np.nan, 4, 6, np.nan, 10]
})

# 给原DataFrame新增列,存储每行的空值列名
df['空值所属列'] = df.isnull().apply(lambda row: ', '.join(row[row].index), axis=1)

# 仅保留存在空值的行,过滤全非空的行
df_with_null = df[df.isnull().any(axis=1)].copy()

方法2:矩阵运算实现(性能高,适合百万级以上大数据集)

用dot运算替代逐行apply,运行效率提升3~10倍,代码如下:

# 直接生成结果字典,key为行索引,value为该行空值列名列表
null_col_map = df.isnull().dot(df.columns + ',').str.rstrip(',').replace('', np.nan).dropna().str.split(',').to_dict()

运行后输出的结果示例:

{
    1: ['col1'],
    2: ['col2'],
    3: ['col3'],
    4: ['col1']
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:24:04