Pandas: Groupby and cut within a group
<p>I have a pandas dataframe which looks like this:</p>

<pre><code>userid   name       date
1           name1    2016-06-04
1           name2    2016-06-05
1           name3    2016-06-04
1           name1    2016-06-06
2           name23   2016-06-01
2           name2    2016-06-01
3           name1    2016-06-03
3           name6    2016-06-03
3           name12   2016-06-03
3           name65   2016-06-04
</code></pre>

<p>So, I want to retain only the rows of the users till the first date events, and cut the rest.</p>

<p>The final df would be as follows:</p>

<pre><code>userid   name       date
1           name1    2016-06-04
1           name2    2016-06-04
2           name23   2016-06-01
2           name2    2016-06-01
3           name1    2016-06-03
3           name6    2016-06-03
3           name12   2016-06-03



userid     int64
name      object
time      object
</code></pre>

<p>The <code>type()</code> of data points in the time column is a <code>datetime.date</code></p>

<p>So, the tasks would involve <code>grouping with respect to userid</code>, <code>sorting according to the date</code>, then <code>retaining only the rows with first(/earliest) date</code>.</p>

<p>You can first sort <code>DataFrame</code> by column <code>date</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow"><code>apply</code></a> <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> - get all rows where is first values:</p>

<pre><code>df = df.sort_values('date')
       .groupby('userid')
       .apply(lambda x: x[x.date == x.date.iloc[0]])
       .reset_index(drop=True)

print (df)
   userid    name       date
0       1   name1 2016-06-04
1       1   name3 2016-06-04
2       2  name23 2016-06-01
3       2   name2 2016-06-01
4       3   name1 2016-06-03
5       3   name6 2016-06-03
6       3  name12 2016-06-03
</code></pre>

python python-2.7 pandas