title: Convert SAS code to Pandas equivalent for groupby.first() and retain function
body: <p>I have SAS code i need to convert into python pandas.</p>
  
  <pre><code>   data df1;
     set df;
         by id;
         retain flag_final;
         if first.id then do;
            if flag eq 0 then flag_final=flag;
            else flag_final=.;
         end;
         else do;
            flag_final=flag_final;
     run;
  </code></pre>
  
  <p>I tried something like this in pandas but its not working i mean am not able to put if else condition into my merge clause. If some one has better idea how to get it done it would be very helpful</p>
  
  <pre><code>  df_temp=df[['id','flag']]
    df1= df.merge(df_temp.groupby('id').first().reset_index(), on='id').rename(
  columns={'flag_x':'flag', 'flag_y':'flag_final'})
  </code></pre>
  
  <p>Note: Even i am not able to understand obove SAS code. So can not put any example input and output dataset. If some knows SAS well can help me to understand it then might be possible i can convert it into pandas. Or you have some approach please suggest.</p>
  
  <p>Edit: Adding input and output dataset:</p>
  
  <p>Input Dataframe:</p>
  
  <pre><code>  import pandas as pd
    import numpy as np
  
   df = pd.DataFrame({'id': [1,1,2,1,2,2,3,3,4,3,3,4,4,4], 'flag': [np.nan,0,1,'p','q',0,"",2,0,'r',np.nan,0,1,np.nan]})
   df=df.sort_values('id')
  
    id      flag
  
    1         NaN
    1         0
    1         p
    2         1
    2         q
    2         0
    3         ""
    3         2
    3         r
    3         NaN
    4         0
    4         0
    4         1
    4        NaN
  </code></pre>
  
  <p>Output dataset:</p>
  
  <pre><code>  id      flag     flag_final
  
    1         NaN     .
    1         0       .
    1         p       .
    2         1       .
    2         q       .
    2         0       .   
    3         ""      .
    3         2       .
    3         r       .
    3         NaN     .
    4         0       0
    4         0       0
    4         1       0
    4        NaN      0
  </code></pre>
  
  <p>I tried like this but its not working:</p>
  
  <pre><code>df=df.sort_values('id')
  df.loc[:,'flag_final']=df
  df['flag_final']=np.where(df['id'].first,np.where(df['flag'].iloc[0]==0,df['flag'],'.'),np.nan)    
  </code></pre>