I hava pandas dataframe where I have to group by some columns. Most groups in the group by only have one row, but a few have more than one row. For each of these, I only want to keep the row with the earliest date.
I've tried both the agg
and filter
functions, but they don't seem to do what I need.
def first(df):
if len(df) > 1:
return df.ix[df['date'].idxmin()]
else:
return df
df.groupby(['id', 'period', 'type').agg(first)
df.sort_values('date').groupby(['id', 'period', 'type']).first()
?