简体   繁体   中英

pandas groupby streak of numbers

I have a dataframe like this:

df = pd.DataFrame({'dir':[0,0,0,1,1,0,1], 'price': [100, 102, 110, 120, 125, 200, 210]})

   dir  price
0    0    100
1    0    102
2    0    110
3    1    120
4    1    125
5    0    200
6    1    210

and I want to groupby 0s and the 1s after it. My desired outcome looks like this:

   dir  price
0    0    100
1    0    102
2    0    110
3    1    120
4    1    125

   dir  price
5    0    200
6    1    210

Using diff with cumsum if it is 1 and 0 you will start count as a new group , so that the diff should be equal( eq ) to -1

for x , y in df.groupby(df.dir.diff().eq(-1).cumsum()): 
    print(y)



   dir  price
0    0    100
1    0    102
2    0    110
3    1    120
4    1    125
   dir  price
5    0    200
6    1    210
d={x: y  for x , y in df.groupby(df.dir.diff().eq(-1).cumsum())}

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