python - 如何在 Python 中对数据进行分组和求和并返回最大的和?
问题描述
假设我的数据如下所示:
新闻标题 | 公司 |
---|---|
细绳 | |
细绳 | |
细绳 | 亚马逊 |
细绳 | 苹果 |
细绳 | 亚马逊 |
细绳 |
如何对公司进行分组并获得最大金额的公司的名称和编号?
我希望能够打印如下内容:
Facebook 在新闻中被提及最多 - 24 次。
我试过这个,但它没有按我想要的方式工作:
df.groupby("company").sum()
解决方案
使用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.
推荐阅读
- php - 用 php 读取大的 json 文件
- image-processing - 您可以将自己的权重传递给 skimage.color.rgb2gray 吗?
- android - E/SQLiteLog: (1) 靠近 "(": 语法
- ios - 无法在 UIInputViewController 中使用 UICollectionView 进行键盘扩展
- python - 使用 Cloud Source 存储库设置 Google Cloud Function 时出现 ModuleNotFoundError
- spring - LDAP Spring Security 不会引发密码策略错误
- c++ - 在我的机器中使用多个 GPU (Intel + Nvidia) - 在它们之间复制数据
- c++ - Qt 应用程序找不到第 3 方 DLL 并崩溃
- python - 继续 for 循环而不进行迭代
- apache-spark - 是否可以使用 Spark Streaming SQL 实时解析来自 Kafka 主题的 JSON 字符串?