我有这个人。数据帧:
Country_FAO type mean_area
0 Afghanistan car 2029000.0
1 Afghanistan car 112000.0
2 Algeria bus 827000.0
3 Algeria bus 2351.0
4 Australia car 6475695.0
5 Australia car 12141000.0
6 Australia bus 293806.0
我想根据mean_area
列中每个值Country_FAO
的总和重新排序此数据框。最终结果应如下所示:
Country_FAO type mean_area
0 Australia car 12141000.0
1 Australia car 6475695.0
2 Australia bus 293806.0
3 Afghanistan car 2029000.0
4 Afghanistan car 112000.0
5 Algeria bus 827000.0
6 Algeria bus 2351.0
澳大利亚首先是因为其3个类别的mean_area
值之和最高。
我试过了:
df_stacked.sort(['Country_FAO', 'mean_area'], ascending=[False, False])
虽然这不起作用,但在进行排序之前它并没有将所有mean_area
加起来。
答案 0 :(得分:1)
我认为您需要在groupby
之后使用transform
然后sort_values
创建新列sort
。最后,您drop
可以reset_index
:
df['sort'] = df.groupby('Country_FAO')['mean_area'].transform(sum)
df['sort'] = df.groupby('Country_FAO')['mean_area'].transform(sum)
df1 = df.sort_values(['sort','Country_FAO', 'mean_area'], ascending=False)
print df1
Country_FAO type mean_area sort
5 Australia car 12141000.0 18910501.0
4 Australia car 6475695.0 18910501.0
6 Australia bus 293806.0 18910501.0
0 Afghanistan car 2029000.0 2141000.0
1 Afghanistan car 112000.0 2141000.0
2 Algeria bus 827000.0 829351.0
3 Algeria bus 2351.0 829351.0
df1 = df1.drop('sort', axis=1).reset_index(drop=True)
print df1
Country_FAO type mean_area
0 Australia car 12141000.0
1 Australia car 6475695.0
2 Australia bus 293806.0
3 Afghanistan car 2029000.0
4 Afghanistan car 112000.0
5 Algeria bus 827000.0
6 Algeria bus 2351.0