简体   繁体   中英

Conditional search in future rows within groupby in pandas

Following is the dataframe I have. The 'Target' column is the desired output.

   Group    Item    Value   Target
    1        0         5      0 
    1        1         4      0
    1        0         6      0
    1        0         3      1
    1        1         2      0
    1        0         1      1
    2        1         8      0
    2        0         9      0
    2        0         7      1

In a given Group , if Item == 1 , then I am trying to find the first future/next row where the Value is less than the corresponding Value for Item == 1 . For example, in the second row, the Item == 1 and the corresponding Value is 4. The first future row where Value is less than 4 is the 4th row which has a Value of 3. Thereby, Target column specifies the find with a 1. It could be possible where two Item==1 has the same future row where conditions satisfy. In that case, we can also have a 1 in Target .

import pandas as pd
df = pd.DataFrame({'Group1': [1,1,1,1,1,1,2,2,2], 'Item': [0,1,0,0,1,0,1,0,0],  'Value': [5,4,6,3,2,1,8,9,7]})
df['next_Value'] = df.groupby(['Group'])['Value'].shift(-1)

Create a help key with cumsum , then we try to get the first value of each group by using transform , and compare each value within the group with the first value , if it is less we should return 1

df['helpkey']=df.groupby('Group').Item.cumsum()
df['New']=(df.Value<df.groupby(['Group','helpkey']).Value.transform('first')).astype(int)
df
Out[51]: 
   Group  Item  Value  Target  helpkey  New
0      1     0      5       0        0    0
1      1     1      4       0        1    0
2      1     0      6       0        1    0
3      1     0      3       1        1    1
4      1     1      2       0        2    0
5      1     0      1       1        2    1
6      2     1      8       0        1    0
7      2     0      9       0        1    0
8      2     0      7       1        1    1

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