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

如何在Pandas DataFrame中删除指定列值为0的行?

如何删除DataFrame中指定列值为0的行

初始DataFrame

初始表格如下:

abcde
99.080.00.00.00.0
0.095.80.00.00.0
0.00.097.80.00.0
0.00.096.70.00.0
0.00.00.098.90.0

对应的初始化代码:

import pandas as pd
df = pd.DataFrame({'a': [99.08, 0.0, 0.0, 0.0, 0.0],
                   'b': [0.0, 95.8, 0.0, 0.0, 0.0],
                   'c': [0.0, 0.0, 97.8, 96.7, 0.0],
                   'd': [0.0, 0.0, 0.0, 0.0, 98.9],
                   'e': [0.0, 0.0, 0.0, 0.0, 0.0],
                   })

处理后的DataFrame

使用pd.melt()重塑数据后,得到仅含两列的DataFrame,其中col2存在大量0值:

col1col2
a99.8
a0.0
a0.0
a0.0
a0.0
b95.8
b0.0
b0.0
c97.8
c0.0
c0.0
c0.0
c96.5
c0.0
d98.9

遇到的问题

需要删除col2值为0的行,但尝试两种方法均失败:

  • 尝试删除全0行时,出现索引错误,原因是any()返回的数据长度与原DataFrame不一致;
  • 尝试删除含0的行时,抛出ValueError: cannot index with multidimensional key错误,提示不能用多维键索引。

解决方法

针对处理后的两列DataFrame,直接筛选col2不等于0的行即可,操作简单且不会报错:

方法1:布尔索引直接筛选

# 假设处理后的DataFrame名为melted_df
melted_df = melted_df[melted_df['col2'] != 0]

方法2:使用query()方法

melted_df = melted_df.query('col2 != 0')

方法3:使用drop()结合布尔索引

melted_df = melted_df.drop(melted_df[melted_df['col2'] == 0].index)

执行后得到的结果如下:

col1col2
a99.8
b95.8
c97.8
c96.5
d98.9

另外,还可以在pd.melt()阶段直接过滤0值,一步到位:

# 初始df转长格式同时过滤0值
melted_df = df.melt(var_name='col1', value_name='col2').query('col2 != 0')

内容的提问来源于stack exchange,提问作者David Siret Marquès

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:18:17