Python 3.x Groupby并在Groupby结果中选择最大行
是否可以在Python/Pandas中对每个groupby结果中的结果进行分组和排序 试图在下面给出的数据中找到每年的顶级通用。尝试了很多使用groupby和sort的方法,但没有成功Python 3.x Groupby并在Groupby结果中选择最大行,python-3.x,dataframe,pandas-groupby,Python 3.x,Dataframe,Pandas Groupby,是否可以在Python/Pandas中对每个groupby结果中的结果进行分组和排序 试图在下面给出的数据中找到每年的顶级通用。尝试了很多使用groupby和sort的方法,但没有成功 Input:: release_year Genere Count 1997 Action 46 1997 Adventure 7 1997 Animation 2 1997 Childr
Input::
release_year Genere Count
1997 Action 46
1997 Adventure 7
1997 Animation 2
1997 Children's 12
1997 Comedy 73
1997 Crime 22
1997 Documentary 6
1997 Drama 81
1997 Horror 6
1997 Mystery 5
1997 Romance 15
1997 Sci-Fi 1
1997 Thriller 9
1997 War 1
1998 Action 12
1998 Adventure 2
1998 Comedy 24
1998 Crime 6
1998 Documentary 2
1998 Drama 21
1998 Film-Noir 2
1998 Horror 3
1998 Romance 4
1998 Thriller 1
Expected Output:
release_year Genere Count
1997 Drama 81
1998 Comedy 24
以下是我的解决方案:
df_res=df.groupby(['release_year','genre'])['Count'].sum().reset_index()
索引=[]
对于df_res['release_year']中的年份。唯一()
df_temp=df_res[df_res.发布年份==年份]
indexs+=列表(df_temp[df_temp['Count']==df_temp['Count'].max()].index)
df_res=df_res.loc[索引]
我不使用“sort()”。我用“max()”代替 试试看:
df=df.sort_值(“计数”,升序=False)
df.groupby(“发布年份”).first()
产出:
一般计数
发布年份
1997年戏剧81
1998年喜剧24
不,不起作用,结果是:1998年惊悚片1,这是不正确的。是的,那是错误的……我犯了一些错误。在循环中,它应该是