Pandas:对值进行排序并忽略 0

Han*_*nan 2 python sorting dataframe pandas

我有以下数据:

product profit
a   32
b   43
c   23
d   34
e   0
f   0
g   -14
h   -12
i   -9
j   -8
k   -3
Run Code Online (Sandbox Code Playgroud)

我想对值进行排序并忽略零。

df.sort_values(by="profit", ascending=False)
Run Code Online (Sandbox Code Playgroud)

预期的输出应该是:

product profit
b   43
d   34
a   32
c   23
k   -3
j   -8
i   -9
h   -12
g   -14
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 5

您可以将掩码和操作链接到pandas

df = df[df['profit'] != 0].sort_values('profit', ascending=False)
Run Code Online (Sandbox Code Playgroud)

或者,为了可读性,您至少还有几个选择:

运算符链接

df = df.loc[df['profit'] != 0]\
       .sort_values('profit', ascending=False)
Run Code Online (Sandbox Code Playgroud)

掩码+排序

mask = df['profit'] != 0
df = df[mask].sort_values('profit', ascending=False)
Run Code Online (Sandbox Code Playgroud)