3

I have a series tt=pd.Series([-1,5,4,0,-7,-9]) .Now i want to sort 'tt'.

the positive values sort in assending order and negative values sort in descending order.Positive values is in front of negative values.

I want to get the following result.

4,5,0,-1,-7,-9

Is there a good way to get the result?

inaMinute
  • 553
  • 2
  • 7
  • 16

2 Answers2

2

You want to sort on tt <= 0 first. Notice this is True for negatives and zero, False for positives. Sorting on this puts positives first. Then sort on tt.abs(). This puts the smallest sized numbers first.

df = pd.concat([tt, tt.abs(), tt.le(0)], axis=1)
df.sort_values([2, 1])[0]

2    4
1    5
3    0
0   -1
4   -7
5   -9
Name: 0, dtype: int64
piRSquared
  • 285,575
  • 57
  • 475
  • 624
1

This is a bit too extended but it gets you your desired output:

import pandas as pd

tt=pd.Series([-1,5,4,0,-7,-9])

pd.concat((tt[tt > 0].sort_values(ascending=True), tt[tt <= 0].sort_values(ascending=False)))

Out[1]: 
0    4
1    5
2    0
3   -1
4   -7
5   -9

Hope this helps.

Abdou
  • 12,931
  • 4
  • 39
  • 42