首页 > 解决方案 > 如何在 Python 中对数据进行分组和求和并返回最大的和?

问题描述

假设我的数据如下所示:

新闻标题 公司
细绳 Facebook
细绳 Facebook
细绳 亚马逊
细绳 苹果
细绳 亚马逊
细绳 Facebook

如何对公司进行分组并获得最大金额的公司的名称和编号?

我希望能够打印如下内容:

Facebook 在新闻中被提及最多 - 24 次。

我试过这个,但它没有按我想要的方式工作:

df.groupby("company").sum()

标签: pythonpandassum

解决方案


使用value_counts

>>> df.company.value_counts().head(1)
Facebook    3
Name: company, dtype: int64

更新

你能告诉我如何用一句话把它打印出来吗?

company, count = list(df.company.value_counts().head(1).items())[0]
print(f'{company} was mentioned in the news the most - {count} times.')

# Output:
Facebook was mentioned in the news the most - 3 times.

推荐阅读