Pandas绘制每个组的值计数直方图

huangapple go评论63阅读模式
英文:

Pandas plot histogram of value counts per group

问题

我有一个数据集:

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

我想要生成一个直方图,每个直方图代表独特的game_id值的分布,根据pandas 2.0.3的版本。

我可以手动实现这个操作,例如,使用years = df.groupby('year'),然后使用years.get_group(2023).value_counts().hist()来处理每一年的数据,但我觉得应该有一个简单的一行代码,将数据传递给hist(),以正确的形式获得小多图。

英文:

I have a dataset:

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

And I'd like to generate one histogram per year of the distribution of unique game_id values (so df['game_id'].value_counts()) using pandas 2.0.3

I can manually do this using e.g. years = df'groupby('year') and then working with each year using years.get_group(2023).value_counts().hist(), but I feel like there should be a simple one-liner to pass the data to hist() in the correct shape to get a small multiples plot.

答案1

得分: 2

以下是要翻译的内容:

假设您想要一个直方图来显示计数:

pd.crosstab(df['game_id'], df['year']).plot.hist(alpha=0.5)

输出:

Pandas绘制每个组的值计数直方图

要生成单独的图表,您可以使用seaborn.displot

import seaborn as sns

sns.displot(data=df.value_counts().reset_index(name='count'),
            x='count', col='year', kind='hist')

输出:

Pandas绘制每个组的值计数直方图

英文:

Assuming you want a histogram of the counts:

pd.crosstab(df['game_id'], df['year']).plot.hist(alpha=0.5)

Output:

Pandas绘制每个组的值计数直方图

For separate graphs, you can use seaborn.displot:

import seaborn as sns

sns.displot(data=df.value_counts().reset_index(name='count'),
            x='count', col='year', kind='hist')

Output:

Pandas绘制每个组的值计数直方图

huangapple
  • 本文由 发表于 2023年8月4日 22:55:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定