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

如何删除2019和2020年col1/col2/col3含NaN的DataFrame行?

处理DataFrame中特定年份指定列的NaN行删除问题

需求说明

删除DataFrame中2019年、2020年数据里,col1、col2、col3三列全部为NaN的行。

原始DataFrame

col1     col2     col3     col4     year
NaN      NaN      NaN      NaN      2018
NaN      NaN      NaN      NaN      2019
NaN      NaN      NaN      100      2019
100      200      100      NaN      2020
NaN      NaN      NaN      200      2020
100      100      150      150      2021

预期处理结果

col1     col2     col3     col4     year
NaN      NaN      NaN      NaN      2018
100      200      100      NaN      2020
100      100      150      150      2021

问题代码分析

你尝试的代码存在三个关键错误:

  • 年份匹配错误:df['year'] == [2019, 2020]无法正确匹配多个年份,需用isin()方法
  • NaN判断错误:df[['col1', 'col2', 'col3']].isnull()返回布尔型DataFrame,直接参与逻辑运算会报错,需用.all(axis=1)判断三列是否全部为NaN
  • 逻辑格式错误:原代码中&前的换行缩进导致语法问题,需确保运算优先级正确

正确实现代码

方法1:直接删除目标行

# 筛选出需要删除的行索引
drop_index = df[(df['year'].isin([2019, 2020])) & (df[['col1', 'col2', 'col3']].isnull().all(axis=1))].index
# 删除行
df.drop(drop_index, inplace=True)

方法2:反向筛选保留需要的行(更直观)

# 保留:年份不在2019/2020,或者年份在但三列不全为NaN的行
df = df[~((df['year'].isin([2019, 2020])) & (df[['col1', 'col2', 'col3']].isnull().all(axis=1)))]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:25:17