简体   繁体   中英

Sort values of a dataframe column based on positive and negative values?

I have df column consisting of +ve and -ve columns.

       A          B
0      a           5
1      b         -13
2      c          15
3      d         -10

And is there a way to sort out +ve values ascending and -ve values descending

       A          B
0      a           5
1      c          15
2      d         -10
3      b         -13

First filter both with boolean indexing , sorting by DataFrame.sort_values and last concat together:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM