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

如何利用字典中的列名检测DataFrame中的NaN值

检测DataFrame指定列NaN值的函数实现

1. 准备依赖与示例数据

首先导入pandas并创建测试用的DataFrame,定义必填列列表:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({
    'Name': ['Alice', None, 'Charlie'],
    'Email': ['alice@example.com', 'bob@example.com', 'charlie@example.com'],
    'Age': [25, None, 30]
})

# 定义必填列
required_cols = ['Name', 'Email']

2. 实现检测函数

核心逻辑是遍历必填列,通过isna().any()判断列中是否存在NaN值,存在则输出指定提示:

def check_required_cols_for_nan(df, required_cols):
    for col in required_cols:
        # 检查当前列是否包含NaN/None值
        if df[col].isna().any():
            print(f"a blank was found in {col}")

3. 调用函数验证

执行函数后会输出符合预期的提示:

check_required_cols_for_nan(df, required_cols)

输出结果:

a blank was found in Name

扩展说明

如果需要同时检测空字符串(如""),可修改判断条件,覆盖空白字符场景:

if (df[col].isna() | df[col].eq("")).any():

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:10:30