[英]pandas dataframe groupby and return nth row unless nth row doesn't exist
我有一个像这样的pandas数据帧:
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
我想按日期和ID对此数据帧进行分组,然后返回该组的第二行以用于其他三列。 如果该组只有一行,那么我希望它返回第一行(即不丢弃该组)。
目前我有以下内容,但这是在该组只有一个实例的情况下。
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
任何帮助将不胜感激! 谢谢。
一种方法是使用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
类似于unutbu 对此问题的处理方法,你可以取前两个(如果你有一个,head(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.