我有一个带有两个键的数据框。我正在寻找key2内项目数量的堆叠条形图(这意味着从完全填充的数据列中获取计数值)。
我拥有的数据框的一小部分是:
Sector industry
Basic Industries Agricultural Chemicals 17
Aluminum 3
Containers/Packaging 1
Electric Utilities: Central 2
Engineering & Construction 12
Name: Symbol, dtype: int64
Key1是行业,Key2是行业。我希望包含基础工业的栏中的符号(计数列表示为行业堆叠)中的值。
我知道如果我做的话,df.reset_index
我将有一列(具有唯一计数器)的(非唯一)行业。有没有一种方法可以简单地将1,2,3列数据分配给pandas图或matplotlib以制作堆叠的条形图?
或者,是否有一种方法可以轻松指定使用上述数据框中的两个键?
我正在寻找经验丰富的人提供的方法指导以及实际语法的帮助。
我刚刚添加了一个新部门来改进示例。
Symbol
Sector industry
Basic Industries Agricultural Chemicals 17
Aluminum 3
Containers/Packaging 1
Electric Utilities: Central 2
Engineering & Construction 22
Basic Industries2 Agricultural Chemicals 7
Aluminum 8
Containers/Packaging 11
Electric Utilities: Central 7
Engineering & Construction 4
假设您的数据["Sector", "industry"]
框已被索引,则需要首先reset_index,然后旋转数据框,最后绘制堆积图。
df.reset_index().pivot_table(index="industry", columns="Sector", values="Symbol").T.plot(kind='bar', stacked=True, figsize=(14, 6))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句