2016-08-18 32 views
3

我有一個熊貓數據幀像這樣:大熊貓數據框中GROUPBY並返回第n行,除非第n行不存在

date  id   person      latitude longitude 
0 2016-07-11 1   rob       41.395279 2.162126 
1 2016-07-11 1   harry      51.485146 0.041339 
2 2016-07-11 1   susan      51.496457 0.051234 
3 2016-07-11 2   lenny      48.863281 2.339698 
4 2016-07-11 2   wendy      51.522469 -0.148812 
5 2016-07-11 3   john      51.490746 -0.022011 

我想這組數據幀的日期和編號,然後再返回的第二行這組爲其他三個欄目。如果該組只有一行,那麼我希望它返回第一行(即不刪除組)。

目前我有以下情況,但是這是放棄那個組只有一個實例的場合。

df_grouped = df.groupby(['date', 'id']).nth(1).reset_index() 

我瞄準的輸出是:

date  id   person      latitude longitude 
0 2016-07-11 1   harry      51.485146 0.041339 
1 2016-07-11 2   wendy      51.522469 -0.148812 
2 2016-07-11 3   john      51.490746 -0.022011 

任何幫助將不勝感激!謝謝。

回答

3

一種方法是根據行的每個組的使用數量apply,拿起行:

df.groupby(['date', 'id']).apply(lambda g: g.iloc[1,:] if g.shape[0] >= 2 else g.iloc[0,:]).reset_index(drop = True) 

#   date id person latitude longitude 
#0 2016-07-11 1 harry 51.485146 0.041339 
#1 2016-07-11 2 wendy 51.522469 -0.148812 
#2 2016-07-11 3 john 51.490746 -0.022011 
3

到unutbu的方法this question類似,您可以把前兩個(如果你有一個,頭(2)將僅返回1)並丟棄保留最後(第二次)出現的副本:

df.groupby(['date', 'id']).head(2).drop_duplicates(['date', 'id'], keep='last') 
Out: 
     date id person latitude longitude 
1 2016-07-11 1 harry 51.485146 0.041339 
4 2016-07-11 2 wendy 51.522469 -0.148812 
5 2016-07-11 3 john 51.490746 -0.022011