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

如何用Pandas 2.0.3按年份分组绘制game_id值计数分布直方图?

问题

现有数据集如下:

game_id year
100     2020
100     2020
100     2020
100     2020
227     2022
227     2022
228     2023
228     2023
228     2023
...
300     2023
300     2023
301     2023
301     2023
301     2023

需要使用Pandas 2.0.3为每个year生成一个直方图,展示唯一game_id的出现次数分布(即df['game_id'].value_counts()的分布)。目前可通过手动分组(如years = df.groupby('year'))后逐个调用years.get_group(2023).value_counts().hist()绘制,但希望用一行代码实现小倍数图(small multiples plot)。

解决方案

可以结合groupby、apply和Matplotlib的子图布局实现一行代码的小倍数图:

(df.groupby('year')['game_id'].apply(lambda x: x.value_counts().hist()).subplots(sharex=True, sharey=True, layout=(1, len(df['year'].unique()))))

说明

  • 先按year分组,对每组的game_id列执行value_counts(),得到该年份下每个game_id的出现次数
  • 对每个年份的次数分布调用hist()生成直方图
  • 通过subplots()统一设置子图布局,sharex和sharey让小倍数图的坐标轴对齐,更便于对比
  • layout参数可根据年份数量调整行列数,比如年份较多时可设为(2, 3)这类布局

如果需要更美观的排版,也可以用Seaborn的FacetGrid配合处理后的数据实现:

import seaborn as sns
sns.FacetGrid(df.groupby('year')['game_id'].value_counts().reset_index(name='counts'), col='year').map(sns.histplot, 'counts')

内容的提问来源于stack exchange,提问作者urschrei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:20:09