如何检查Pandas DataFrame列中的float类型NaN值
检查Pandas DataFrame列中的NaN值
你写的if df['column'] == 'nan':这种方式行不通,原因有两点:
- 这里的NaN是float类型的特殊值,不是字符串"nan",两者类型和值都不相等;
- 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
相关产品推荐
相关产品推荐

