如何删除DataFrame中指定全NaN列及特定列全NaN的行
Pandas DataFrame 处理NaN列/行的两种场景解决方案
需求1:删除指定列中全为NaN的列
解决方案
先筛选出指定列中所有值均为NaN的列,再从DataFrame中删除这些列:
import pandas as pd # 替换为实际需要检查的列名 cols_to_check = ['列名1', '列名2', '列名3'] # 收集指定列中全为NaN的列名 cols_to_drop = [col for col in cols_to_check if df[col].isna().all()] # 删除目标列 df = df.drop(cols_to_drop, axis=1)
说明
df[col].isna().all():判断单列所有值是否均为NaNaxis=1:告诉drop()方法操作对象是列而非行
需求2:删除指定列组全为NaN的行
原始DataFrame
no d1 d2 d3 c1 c2 c3 0 59890 28.4 32.2 31.3 40.7 40.0 39.6 1 55679 NaN 32.8 31.5 37.3 39.2 39.4 2 58900 NaN NaN NaN NaN NaN NaN 3 76522 34.0 32.4 32.6 45.4 NaN 46.9 4 89525 32.7 31.9 32.0 44.1 44.4 46.1 ... ... ... ... ... ... ... ...
解决方案
使用dropna()方法,指定检查的列子集并设置仅删除全NaN的行:
import pandas as pd # 指定需要检查的列 target_cols = ['d1', 'd2', 'd3', 'c1', 'c2', 'c3'] # 删除指定列全为NaN的行 df_cleaned = df.dropna(subset=target_cols, how='all')
预期输出
no d1 d2 d3 c1 c2 c3 0 59890 28.4 32.2 31.3 40.7 40.0 39.6 1 55679 NaN 32.8 31.5 37.3 39.2 39.4 3 76522 34.0 32.4 32.6 45.4 NaN 46.9 4 89525 32.7 31.9 32.0 44.1 44.4 46.1 ... ... ... ... ... ... ... ...
说明
subset=target_cols:限定仅检查指定的6列,忽略其他列的NaN情况how='all':仅当指定列的所有值都是NaN时,才删除对应行
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

