Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Sort value and ignore 0

I've following data:

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

I want to sort values and ignore the zero.

df.sort_values(by="profit", ascending=False)

The expected output should be:

product profit
b   43
d   34
a   32
c   23
k   -3
j   -8
i   -9
h   -12
g   -14
like image 699
Hannan Avatar asked Oct 17 '25 05:10

Hannan


1 Answers

You can chain masks and operations with pandas:

df = df[df['profit'] != 0].sort_values('profit', ascending=False)

Or, for readability, you have at least a couple more options:

Operator chaining

df = df.loc[df['profit'] != 0]\
       .sort_values('profit', ascending=False)

Mask + sort

mask = df['profit'] != 0
df = df[mask].sort_values('profit', ascending=False)
like image 74
jpp Avatar answered Oct 18 '25 17:10

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!