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

如何移除除指定列外其余列均为空的DataFrame整行数据?

移除除指定列外其余列全为空的行

问题场景

给定如下DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({"col1": ["s1", "s2", "s3", "s4", "s5", "s6"],
                   "col2": [41, np.nan, np.nan, np.nan, np.nan, 61],
                   "col3": [24, 51, np.nan, np.nan, np.nan, 84],
                   "col4": [53, 64, 81, np.nan, np.nan, np.nan],
                   "col5": [43, 83, 47, 12, np.nan, 19]})

需要移除除col1外其余列全为空的行(即索引为4的行),直接使用df.dropna(how="all")无效,因为该行col1存在值。

解决方案

方法1:使用dropna的subset参数

通过subset指定需要检查空值的列(即除col1外的所有列),配合how="all"删除这些列全为空的行:

# 手动指定要检查的列
df_clean = df.dropna(subset=["col2", "col3", "col4", "col5"], how="all")

# 若列较多,自动生成要检查的列列表
cols_to_check = df.columns.difference(["col1"])
df_clean = df.dropna(subset=cols_to_check, how="all")

方法2:布尔索引筛选

先判断除col1外的列是否不全为空,再筛选符合条件的行:

# 方式1:删除col1后判断每行是否全为空,取反筛选
df_clean = df[~df.drop("col1", axis=1).isna().all(axis=1)]

# 方式2:通过位置索引选取除第一列外的所有列,判断是否有非空值
df_clean = df[df.iloc[:, 1:].notna().any(axis=1)]

结果验证

执行上述任意方法后,得到的结果如下:

col1   col2   col3   col4   col5
0   s1     41.0   24.0   53.0   43.0
1   s2     NaN    51.0   64.0   83.0
2   s3     NaN    NaN    81.0   47.0
3   s4     NaN    NaN    NaN    12.0
5   s6     61.0   84.0   NaN    19.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:05:20