gpt4 book ai didi

python - 使用 pandas 按列值分组条形图

转载 作者:行者123 更新时间:2023-12-01 09:10:26 25 4
gpt4 key购买 nike

我正在尝试显示编码为列值的类别的分组条形图(在我的示例中为 col2)

条形图的图例必须显示 col2 中编码的值,因此 TrueFalse 并且条形图应根据这些进行分组值。

df = pd.DataFrame({
'col1': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'A', 'A', 'A', 'B'],
'col2': [True, False, True, True, False, True, False, False, False, False, True],
})
df.groupby('col1')['col2'].count().plot(kind = 'bar', legend=True)

enter image description here

相反,我希望看到类似的内容:

enter image description here

最佳答案

我认为你需要:

df.groupby(['col1', 'col2']).agg('size').unstack().plot(kind = 'bar', legend=True)

enter image description here

关于python - 使用 pandas 按列值分组条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51704243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com