[英]pandas groupby & lambda function to return nlargest(2)
Please see pandas df:请参阅 pandas df:
pd.DataFrame({'id': [1, 1, 2, 2, 2, 3],
'pay_date': ['Jul1', 'Jul2', 'Jul8', 'Aug5', 'Aug7', 'Aug22'],
'id_ind': [1, 2, 1, 2, 3, 1]})
I am trying to groupby 'id' and 'pay_date'.我正在尝试按“id”和“pay_date”分组。 I only want to keep df['id_ind'].nlargest(2) in the dataframe after grouping by 'id' and 'pay_date'.
在按“id”和“pay_date”分组后,我只想将 df['id_ind'].nlargest(2) 保留在 dataframe 中。 Here is my code:
这是我的代码:
df = pd.DataFrame(df.groupby(['id', 'pay_date'])['id_ind'].apply(
lambda x: x.nlargest(2)).reset_index()
This does not work, as the new df returns all the records.这不起作用,因为新的 df 返回所有记录。 If it worked, 'id'==2 would only appear twice in the df, as there are 3 records and I only want the 2 largest by 'id_ind'.
如果它有效,'id'==2 只会在 df 中出现两次,因为有 3 条记录,我只想要 2 最大的 'id_ind'。
My desired output:我想要的 output:
pd.DataFrame({'id': [1, 1, 2, 2, 3],
'pay_date': ['Jul1', 'Jul2', 'Aug5', 'Aug7', 'Aug22'],
'id_ind': [1, 2, 2, 3, 1]})
Sort on id_ind
and doing groupby.tail
对
id_ind
进行排序并进行groupby.tail
df_final = (df.sort_values('id_ind').groupby('id').tail(2)
.sort_index()
.reset_index(drop=True))
Out[29]:
id id_ind pay_date
0 1 1 Jul1
1 1 2 Jul2
2 2 2 Aug5
3 2 3 Aug7
4 3 1 Aug22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.