简体   繁体   English

如何使用 Python Pandas 对组的平均值进行排序?

[英]How do I sort the average of a group using Python Pandas?

The data frame has country, height, and many other columns.数据框有国家、高度和许多其他列。 I want to report the average height by country and sort it with the highest average on top.我想按国家/地区报告平均身高,并将最高的平均身高排在首位。 I am stuck at the sort.我被困在那种情况下。 So far, I have this.到目前为止,我有这个。

cH = df.("Country")["Height"].mean()

This allowed me to find the average height per country.这使我能够找到每个国家/地区的平均身高。 However, now I need to sort this.但是,现在我需要对此进行排序。

Try this:尝试这个:

    df= pd.DataFrame({
    'Country':['a','b','a','b'],
    'Height':[10,20,30,40]
})

df.groupby("Country", as_index=False).Height.mean().sort_values('Height', ascending=False)

Output Output

    Country Height
1   b       30
0   a       20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM