3 回答
TA贡献1829条经验 获得超7个赞
DataFrame.sort_values与 一起使用GroupBy.head:
df = df.sort_values(['id','year'], ascending=[True, False]).groupby('id').head(3)
print (df)
year id
0 2019 x1
2 2017 x1
3 2013 x1
4 2018 x2
6 2013 x2
5 2012 x2
如果顺序应该相同,请添加DataFrame.sort_index:
df = df.sort_values(['id','year'], ascending=[True, False]).groupby('id').head(3).sort_index()
print (df)
year id
0 2019 x1
2 2017 x1
3 2013 x1
4 2018 x2
5 2012 x2
6 2013 x2
TA贡献1827条经验 获得超8个赞
使用GroupBy.nlargest:
df = df.groupby('id')['year'].nlargest(3).reset_index().drop(columns='level_1')
id year
0 x1 2019
1 x1 2017
2 x1 2013
3 x2 2018
4 x2 2013
5 x2 2012
确保它year有一个intdtype:
df['year'] = df['year'].astype(int)
TA贡献1842条经验 获得超22个赞
使用 for 循环来解决这个问题怎么样(我喜欢循环):
id_unique = df.id.unique()
df_new = pd.DataFrame(columns = df.columns)
for i in id_unique:
df_new = pd.concat([df_new, df[df['id'] == i ].sort_values(['year'], ascending= [False]).head(3)], axis=0)
添加回答
举报
