title: Pandas groupby agg/apply with different functions for different rows in group
body: <p>I'm trying to perform a groupby aggregation.  My dummy Dataframe looks like this:</p>
  
  <pre><code>print (df)
      ID  Industry  Value 1  Value 2
  0    1   Finance     0.25       99
  1    1   Finance     0.50       73
  2    1   Finance     0.25       53
  3    1  Teaching     0.75       80
  4    1  Teaching     0.25       78
  5    1  Teaching     0.50       99
  6    2   Finance     0.50       75
  7    2   Finance     0.25       56
  8    2   Finance     0.25       80
  9    2  Teaching     0.50       79
  10   3   Finance     0.25       61
  11   3   Finance     0.75       87
  12   3   Finance     0.75       97
  13   3   Finance     0.25       99
  14   3   Finance     0.25       76
  15   3  Teaching     0.25       73
  16   3  Teaching     0.75       68
  17   3  Teaching     0.25       59
  18   3  Teaching     0.25       60
  </code></pre>
  
  <p>I want to group by ID and Industry and I want to create a new field called say "Expected".  Expected will be equal to:</p>
  
  <ul>
  <li>If it's the first row of the group, Value 1 + Value 2</li>
  <li>If it's any other row in the group Expected value of the row above in that group <em>minus</em> (Value 1 * Value 2) for the current row, so that Expected value looks as follows:</li>
  </ul>
  
  <p><a href="https://i.stack.imgur.com/V26aY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V26aY.jpg" alt="enter image description here"></a></p>
  
  <p>I'd like to avoid a loop if possible.  Any help would appreciated as multiple attempts using iloc, groupby agg, groupby transform have come up short for me.</p>