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

Pandas:对数据排序并忽略值为0的行

解决方案

没问题,你只需要在排序前先过滤掉profit值为0的行,就能得到你想要的结果。

原始数据

product profit
a       32
b       43
c       23
d       34
e       0
f       0
g       -14
h       -12
i       -9
j       -8
k       -3

当前代码的问题

你现有的代码df.sort_values(by="profit", ascending=False)仅实现了按profit降序排序,但没有排除profit为0的行,所以需要补充过滤步骤。

修正后的代码

# 先过滤掉profit为0的记录,再执行排序
result_df = df[df['profit'] != 0].sort_values(by="profit", ascending=False)

执行结果

product profit
b       43
d       34
a       32
c       23
k       -3
j       -8
i       -9
h       -12
g       -14

简单解释一下:

  • df[df['profit'] != 0]:这一步会筛选出所有profit值不等于0的行,排除掉e和f这两条记录;
  • 之后调用sort_values(by="profit", ascending=False),就会按profit从高到低排序,得到你期望的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:01:00