简体   繁体   中英

Pandas - count groupBy results

I am trying to get a group of the most popular names by country using pandas. I have gotten half way as seen in the snippet but I am unclear how to convert groupedByCountry into a sorted table.

import math
import pandas
csv = pandas.read_csv("./name_country.csv.gz", compression="gzip")

data = csv[["name",'country']]

filtered = roleIni[data.country.notnull()]

groupedByCountry = filtered.groupby("country")

You can use groupby size and then use nlargest :

In [11]: df = pd.DataFrame([["andy", "GB"], ["bob", "US"], ["chris", "GB"]], columns=["name", "country"])

In [12]: df.groupby("country").size().nlargest(1)
Out[12]:
country
GB    2
dtype: int64

It's probably more efficient however to do a direct value_counts on the column, and then take the head ( head(n) will get the top n most popular countries):

In [21]: df["country"].value_counts().head(1)
Out[21]:
GB    2
Name: country, dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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