2016-12-27 118 views
1

我hava熊貓數據幀,我必須按某些列分組。組中的大多數組只有一行,但少數組有多行。對於其中的每一個,我只想保持最早的日期。 我已經嘗試了aggfilter的功能,但他們似乎沒有做我需要的。熊貓羣體,然後選擇一行

def first(df): 
     if len(df) > 1: 
      return df.ix[df['date'].idxmin()] 
     else: 
      return df 

df.groupby(['id', 'period', 'type').agg(first) 
+1

'df.sort_values( '日期')。GROUPBY([ 'ID', '期間', '類型' ])。first()'? – MaxU

回答

4

按日期排序,然後只抓住第一行。

df.sort_values('date').groupby(['id', 'period', 'type']).first() 
2

還可以使用nsmallest()

df.groupby(['id', 'period', 'type']).apply(lambda g: g.nsmallest(1, "date")) 
2

過濾df與最小日期的指標。
idxmin讓你知道該索引。然後傳遞給loc

df.loc[df.groupby(['id', 'period', 'type']).date.idxmin()] 

考慮df

df = pd.DataFrame([ 
     ['a', 'q', 'y', '2011-03-31'], 
     ['a', 'q', 'y', '2011-05-31'], 
     ['a', 'q', 'y', '2011-07-31'], 
     ['b', 'q', 'x', '2011-12-31'], 
     ['b', 'q', 'x', '2011-01-31'], 
     ['b', 'q', 'x', '2011-08-31'], 
    ], columns=['id', 'period', 'type', 'date']) 
df.date = pd.to_datetime(df.date) 

df 

    id period type  date 
0 a  q y 2011-03-31 
1 a  q y 2011-05-31 
2 a  q y 2011-07-31 
3 b  q x 2011-12-31 
4 b  q x 2011-01-31 
5 b  q x 2011-08-31 

然後

df.loc[df.groupby(['id', 'period', 'type']).date.idxmin()] 

    id period type  date 
0 a  q y 2011-03-31 
4 b  q x 2011-01-31