Pandas计数分组结果

2024-09-29 20:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过使用熊猫的国家来获得一组最流行的名字。如代码片段所示,我已经完成了一半,但我不清楚如何将groupedByCountry转换为排序表。你知道吗

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")

Tags: csv代码nameimportpandasreaddata排序
1条回答
网友
1楼 · 发布于 2024-09-29 20:31:14

您可以使用groupby^{},然后使用^{}

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

不过,在列上直接^{},然后选择^{}head(n)将获得前n名最受欢迎的国家)可能更有效:

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

相关问题 更多 >

    热门问题