How to find positive survey streak for multiple employees using pandas

Viewed 40

I have the following data frame. I want to find a maximum positive survey streak for multiple agents.

data = {'Name':['Ramu', 'Aana', 'Rafi', 'Ramu','Aana','Ramu','Aana','Rafi','Ramu','Aana','Rafi','Rafi','Rafi'], 'Score':[1,0,1,1,1,1,1,0,1,1,0,1,1]} 

Name    Survey  
Ramu    1       
Aana    0       
Rafi    1       
Ramu    1       
Aana    1       
Ramu    1       
Aana    1       
Rafi    0       
Ramu    1       
Aana    1 
Rafi    0
Rafi    1
Rafi    1

I want the output to be like this. Please help me to achieve this.

Name    positive_survey_max_streak  
Ramu    4      
Aana    3       
Rafi    2       
1 Answers

We can create a function which resets the cumsum at 0. It basically substracts 1 where the Score = 0. Then we use GroupBy twice:

def cumsum_reset(arr):
    arr = arr.cumsum() - arr.cumsum().where(~arr).ffill().fillna(0).astype(int)

    return arr

dfg = (
    df['Score'].eq(1)
    .groupby(df['Name']).apply(cumsum_reset)
    .groupby(df['Name']).max()
    .reset_index(name='positive_survey_max_streak')
)

Output

   Name  positive_survey_max_streak
0  Aana                           3
1  Rafi                           2
2  Ramu                           4
Related