python - 绘制分组的 Pandas 数据框

标签 python pandas matplotlib bar-chart

我花了几个小时寻找答案,但我似乎找不到答案。

长话短说,我有一个数据框。以下代码将生成有问题的数据框(尽管使用随机数匿名):

variable1 = ["Attribute 1","Attribute 1","Attribute 1","Attribute 1","Attribute 1","Attribute 1","Attribute 2","Attribute 2",
         "Attribute 2","Attribute 2","Attribute 2","Attribute 2","Attribute 3","Attribute 3","Attribute 3","Attribute 3",
         "Attribute 3","Attribute 3","Attribute 4","Attribute 4","Attribute 4","Attribute 4","Attribute 4","Attribute 4",
         "Attribute 5","Attribute 5","Attribute 5","Attribute 5","Attribute 5","Attribute 5"]


variable2 = ["Property1","Property2","Property3","Property4","Property5","Property6","Property1","Property2","Property3",
         "Property4","Property5","Property6","Property1","Property2","Property3",
         "Property4","Property5","Property6","Property1","Property2","Property3","Property4",
         "Property5","Property6","Property1","Property2","Property3","Property4","Property5","Property6"]

number = [93,224,192,253,186,266,296,100,135,169,373,108,211,194,164,375,211,71,120,334,59,164,348,50,249,18,251,343,172,41]

bar = pd.DataFrame({"variable1":variable1, "variable2":variable2, "number":number})

bar_grouped = bar.groupby(["variable1","variable2"]).sum()

结果应该是这样的:

enter image description here

第二个:

enter image description here

我一直在尝试用条形图绘制它们,并将属性作为组,将不同的属性作为条形图。与此类似(虽然手动绘制在 Excel 中)。我更愿意在分组的 datafarme 中执行此操作,以便能够使用不同的分组进行绘图,而无需每次都重置索引。

enter image description here

我希望这是清楚的。

非常感谢对此的任何帮助。

谢谢! :)

最佳答案

我不会费心创建您的 groupby 结果(因为您没有聚合任何东西)。这是一个枢轴


bar.pivot('variable2', 'variable1', 'number').plot(kind='bar')

plt.tight_layout()
plt.show()

enter image description here


如果需要聚合,您仍然可以从bar开始并使用pivot_table

bar.pivot_table(index='variable2', columns='variable1', values='number', aggfunc='sum')

关于python - 绘制分组的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376362/

相关文章:

python - 使用 Pandas 查找具有 Null 的 2 列之间的差异

matplotlib - 在没有数据数组的情况下在 matplotlib 中绘制箱线图?

python - 如何在本地运行 Postgres

python程序从用户输入生成n*n矩阵

python - 如何使用opencv轮廓裁剪对象/从图像中获取位置信息

python - 在 python 中基于分钟的日期时间列中每隔 n 分钟采样一次

Python ArgParse Subparsers 并链接到正确的函数

python - 从 Pandas 数据框中的一组对中获取所有连接的组件

python - 为什么当 PyPi 显示版本 1.0.0 时 pip 安装 matplotlib 版本 0.91.1?

python - 将 pandas 数据框可视化为热图时出现类型错误