title: Pandas dataframe apply refer to previous row to calculate difference
body: <p>I have the following pandas dataframe containing 2 columns (simplified). The first column contains <em>player names</em> and the second column contains <em>dates</em> (<code>datetime</code> objects):</p>
  
  <pre><code>  player    date
    A         2010-01-01
    A         2010-01-09
    A         2010-01-11
    A         2010-01-15
    B         2010-02-01
    B         2010-02-10
    B         2010-02-21
    B         2010-02-23
  </code></pre>
  
  <p>I want to add a column <em>diff</em> which represents the time difference in days <em>per player</em>. The result should look like this:</p>
  
  <pre><code>  player    date            diff
    A         2010-01-01      0
    A         2010-01-09      8
    A         2010-01-11      2
    A         2010-01-15      4
    B         2010-02-01      0
    B         2010-02-10      9
    B         2010-02-21      11
    B         2010-02-23      2
  </code></pre>
  
  <p>The first row has <code>0</code> for diff, because there is no earlier date. The second row shows <code>8</code>, because the difference between <code>2010-01-01</code> and <code>2010-01-09</code> is eight days.</p>
  
  <p>The problem is not calculating the day-difference between two <code>datetime</code> objects. I am just not sure on how to add the new column. I know, that I have to make a <code>groupby</code> first (<code>df.groupby('player')</code>) and then use <code>apply</code> (or maybe <code>transform</code>?). However, I am stuck, because for calculating the difference, I need to refer to the <em>previous row</em> in the apply-function, and I don't know how to do that, if possible at all.</p>
  
  <p>Thank you very much.</p>
  
  <p><strong>UPDATE:</strong>
  After trying both proposed solutions below, I figured out that they did not work with my code. After much headache, I found out that my data had duplicate indices. So after I found out that I have duplicate indices, a simple <code>df.reset_index()</code> solved my issue and the proposed solutions worked. Since both solutions work, but I can only mark one as correct, I will choose the more concise/shorter solution. Thanks to both of you, though!</p>