You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas实现各国年度订阅量最大值查询求助

找出每个国家订阅量总和最高的年份

这里有两种实用方法可以实现你的需求:


方法一:用 idxmax 定位最大值行

先把你当前的分组结果转换成DataFrame(当前返回的是Series),再按国家分组找到订阅量总和最大的行索引,最后提取这些行即可:

# 生成带列名的分组结果DataFrame
subs_summary = netf.query('country != "unspecified"')\
    .groupby(['country', 'created_year'], sort=True)['subscribers']\
    .sum()\
    .reset_index(name='total_subscribers')

# 找到每个国家订阅量总和最大的行的索引
max_rows_idx = subs_summary.groupby('country')['total_subscribers'].idxmax()

# 获取最终结果
final_result = subs_summary.loc[max_rows_idx]

方法二:用 transform 筛选最大值

另一种思路是先计算每个国家的订阅量最大值,再直接筛选出等于该值的行:

subs_summary = netf.query('country != "unspecified"')\
    .groupby(['country', 'created_year'], sort=True)['subscribers']\
    .sum()\
    .reset_index(name='total_subscribers')

# 给每行添加对应国家的最大订阅量列
subs_summary['country_max_subs'] = subs_summary.groupby('country')['total_subscribers'].transform('max')

# 筛选符合条件的行并移除临时列
final_result = subs_summary[subs_summary['total_subscribers'] == subs_summary['country_max_subs']].drop(columns='country_max_subs')

补充说明

  • 如果某个国家存在多个年份的订阅量总和相同且均为最大值,两种方法都会保留所有这些行(比如某国2010和2012年订阅总和一致且最高,结果会显示这两行)。
  • 你的created_year列是字符串格式(例如'2006.0'),若需转换为整数年份,可添加一行:
subs_summary['created_year'] = subs_summary['created_year'].str.replace('.0', '').astype(int)

内容的提问来源于stack exchange,提问作者Owen Tamuno Gilbert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:02:32