在 pandas 中分组并自动递增组ID [英] Grouping and auto incrementing group id in pandas
本文介绍了在 pandas 中分组并自动递增组ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有python 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
数量是累计的购买/购买数量,当其为0时,持仓持平.
Qty is cummulative qty sold/bought, when it goes to 0, the position is flat.
我想分配组ID,以便从下订单中提取已执行的交易.
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
在没有显式遍历行和分配Trade_Group值的情况下,如何 可以构造Trade_group列吗?
With out explicity iterating through rows and assigning Trade_Group values, how can I construct Trade_group column?
感谢您的时间!
推荐答案
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()
这篇关于在 pandas 中分组并自动递增组ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文