根据正值和负值对数据框列的值进行排序?

2 python pandas

我有 df 列,由 +ve 和 -ve 列组成。

       A          B
0      a           5
1      b         -13
2      c          15
3      d         -10
Run Code Online (Sandbox Code Playgroud)

有没有办法对 +ve 值升序和 -ve 值降序进行排序

       A          B
0      a           5
1      c          15
2      d         -10
3      b         -13
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

首先使用boolean indexing、排序依据DataFrame.sort_values和 最后concat一起过滤:

mask = df['B'].gt(0)
df = pd.concat([df[mask].sort_values('B'),
                df[~mask].sort_values('B', ascending=False)], ignore_index=True)
print (df)
   A   B
0  a   5
1  c  15
2  d -10
3  b -13
Run Code Online (Sandbox Code Playgroud)