熊猫:排序值并忽略0

时间:2018-05-29 22:03:21

标签: python pandas sorting dataframe

我关注的数据是:

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)

预期输出应为:

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

1 个答案:

答案 0 :(得分:3)

您可以使用pandas链接掩码和操作:

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

或者,为了便于阅读,您至少还有几个选项:

操作员链接

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

面具+排序

mask = df['profit'] != 0
df = df[mask].sort_values('profit', ascending=False)
相关问题