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

如何检查Pandas DataFrame列中的float类型NaN值

检查Pandas DataFrame列中的NaN值

你写的if df['column'] == 'nan':这种方式行不通,原因有两点:

  1. 这里的NaN是float类型的特殊值,不是字符串"nan",两者类型和值都不相等;
  2. NaN的特殊性质是自身不等于自身,哪怕你写df['column'] == np.nan也会返回False。

下面是两种正确的处理方式:

针对单个元素判断

如果要检查DataFrame中某个具体位置的元素是否为NaN,用Pandas自带的pd.isna()或者NumPy的np.isnan():

import pandas as pd
import numpy as np

# 示例:检查第1行的该列元素
if pd.isna(df['column'].iloc[0]):
    print('hi')

# 或者用numpy的方法
if np.isnan(df['column'].iloc[0]):
    print('hi')

针对整列批量处理

如果要对整列所有NaN值对应的行执行操作,用布尔索引更高效:

# 筛选出该列为NaN的所有行
nan_rows = df[df['column'].isna()]

# 对这些行执行操作,比如逐行打印
for _, _ in nan_rows.iterrows():
    print('hi')

# 或者用apply逐元素处理
df['column'].apply(lambda x: print('hi') if pd.isna(x) else x)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:45:34