Search code examples
pythonpandastrading

Grouping and auto incrementing group id in pandas


I have python pandas data frame

trades = pd.DataFrame({"Qty":[-25,0,25,50,75,0,25,0,-25,0,-25,-50,0,-25,50,0]})
print trades
    Qty
0   -25
1     0
2    25
3    50
4    75
5     0
6    25
7     0
8   -25
9     0
10  -25
11  -50
12    0
13  -25
14   50
15    0

Qty is cummulative qty sold/bought, when it goes to 0, the position is flat.

I want to assign group ids, so that I can extract executed trades from the orders placed.

    Qty     Trade_Group
0   -25     1
1     0     1
2    25     2
3    50     2
4    75     2
5     0     2
6    25     3
7     0     3
8   -25     4
9     0     4
10  -25     5
11  -50     5
12    0     5
13  -25     6
14   50     6
15    0     6

With out explicity iterating through rows and assigning Trade_Group values, how can I construct Trade_group column?

Thanks for the time!


Solution

  • trades = pd.DataFrame({"Qty":[-25,0,25,50,75,0,25,0,-25,0,-25,-50,0,-25,50,0]})
    trades["group"] = (trades.Qty == 0).shift(1).fillna(0).cumsum()