Python pandas groupby for first date

I am considering a group of temporary employees in the field of data. I use pandas and I need to get the first date "apnt_ymd" for each person in the list. So for Green I need 2011-04-10. For LEMERISE I need 2011-05-08.

In:name = temphires[['ssno','nm_emp_lst','nm_emp_fst','apnt_ymd']].sort('ssno')
   name.drop_duplicates(['apnt_ymd'])

ssno    nm_emp_lst  nm_emp_fst  apnt_ymd
299769   123456789   GREENE  ALTON  2014-05-04
192323   123456789   GREENE  ALTON  2013-04-07
192324   123456789   GREENE  ALTON  2012-04-08
102872   123456789   GREENE  ALTON  2011-04-10
175701   987654321   DUBE    JEFFREY    2013-04-21
177583   777888999   IRVING  SARA   2013-05-13
4785     777888999   IRVING  SARA   2012-05-16
222300   444444444   LEMERISE    GEORGE 2013-04-14
24386    444444444   LEMERISE    GEORGE 2012-03-25
24434    444444444   LEMERISE    GEORGE 2011-05-08

Thank you

+4
source share
1 answer

A couple of assumptions that yours is apnt_ymdalready a date or a date if you cannot do this:

df['apnt_ymd'] = pd.to_datetime(df['apnt_ymd'])

So, we can groupbycolumn nm_emp_listand then calculate the lowest value for apnt_ymdand return the index using idxmin(). Then we can use this index for the original df to display the desired result:

In [4]:

df.loc[df.groupby('nm_emp_lst')['apnt_ymd'].idxmin()]
Out[4]:
       id       ssno nm_emp_lst nm_emp_fst   apnt_ymd
4  175701  987654321       DUBE    JEFFREY 2013-04-21
3  102872  123456789     GREENE      ALTON 2011-04-10
6   84785  126644444     IRVING       SARA 2012-05-16
9   24434  777888999   LEMERISE     GEORGE 2011-05-08
+5
source

All Articles