Best approach to create time difference variable by id
<p>I am working with a pandas df that looks like this:</p>

<pre><code>ID time
34  43
2   99
2   20
34  8
2   90
</code></pre>

<p>What would be the best approach to a create variable that represents the difference from the most recent time per ID?</p>

<pre><code>ID time diff
34  43   35
2   99   9
2   20   NA
34  8    NA
2   90   70
</code></pre>

<p>Here's one possibility</p>

<pre><code>df["diff"] = df.sort_values("time").groupby("ID")["time"].diff()
df

    ID  time diff
0   34  43   35.0
1   2   99   9.0
2   2   20   NaN
3   34  8    NaN
4   2   90   70.0
</code></pre>

python pandas