Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas groupby for first date

I am looking at a group of temporary employees in a dataframe. I am using pandas and I need to get the first 'apnt_ymd' date for each person in the list. So for Greene, 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

like image 321
Dave Avatar asked Sep 23 '14 20:09

Dave


1 Answers

A couple assumptions, that your apnt_ymd is a date or datetime already, if not you can convert doing this:

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

So we can groupby the nm_emp_list column and then calculate the lowest value for apnt_ymd and return the index using idxmin(). We can then use this index against 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
like image 73
EdChum Avatar answered Oct 06 '22 04:10

EdChum