Iterate through the rows of a dataframe and reassign minimum values by group
<p>I am working with a dataframe that looks like this.</p>

<pre><code>  id time diff
0 0   34   nan
1 0   36   2
2 1   43   7
3 1   55   12
4 1   59   4
5 2   2    -57
6 2   10   8
</code></pre>

<p>What is an efficient way find the minimum values for 'time' by id, then set 'diff' to nan at those minimum values. I am looking for a solution that results in:</p>

<pre><code>   id time diff
0 0   34   nan
1 0   36   2
2 1   43   nan
3 1   55   12
4 1   59   4
5 2   2    nan
6 2   10   8
</code></pre>

<p>You can group the time by id and calculate a logical vector where if the time is minimum within the group, the value is True, else False, and use the logical vector to assign <code>NaN</code> to the corresponding rows:</p>

<pre><code>import numpy as np
import pandas as pd
df.loc[df.groupby('id')['time'].apply(lambda g: g == min(g)), "diff"] = np.nan

df
#  id   time    diff
#0  0     34    NaN
#1  0     36    2.0
#2  1     43    NaN
#3  1     55    12.0
#4  1     59    4.0
#5  2      2    NaN
#6  2     10    8.0
</code></pre>

python pandas