Search code examples
pythonpandasdataframegroup-by

Python groupby rank in two different directions


I have a dataframe, d:

    Position    Operation   Side    Price   Size
9   9   0   1   0.7289  -16
8   8   0   1   0.729   -427
7   7   0   1   0.7291  -267
6   6   0   1   0.7292  -15
5   5   0   1   0.7293  -16
4   4   0   1   0.7294  -16
3   3   0   1   0.7295  -426
2   2   0   1   0.7296  -8
1   1   0   1   0.7297  -14
0   0   0   1   0.7298  -37
10  0   0   0   0.7299  6
11  1   0   0   0.73    34
12  2   0   0   0.7301  7
13  3   0   0   0.7302  9
14  4   0   0   0.7303  16
15  5   0   0   0.7304  15
16  6   0   0   0.7305  429
17  7   0   0   0.7306  16
18  8   0   0   0.7307  265
19  9   0   0   0.7308  18

Using the below for updates to d to recalculate Position:

d['Position'] = d.groupby('Side')['Price'].rank().astype('int').sub(1)

But as the order of the sort is different for each Side grouping, is there a way to sort ascending for one group and descending for another?


Solution

  • Code

    I think simple solution is to rank the groups by multiplying their Price by -1, where the ranking order should be reversed.

    cond = d['Side'].eq(1) # you can use isin when apply to multiple group
    d['rank'] = (
        d['Price']
        .mask(cond, d['Price'].mul(-1))
        .groupby(d['Side']).rank().astype('int').sub(1)
    )