python-3.x - Python Pandas 将表格透视为饼图

标签 python-3.x matplotlib pandas

使用总计百分比(数据透视表中所有数据的总和)将以下数据透视表中的所有非零值更改为饼图的最佳方法是什么?

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'axis1': ['Unix','Window','Apple','Linux'],
                 'A': [3,0,1,10],
                 'B': [1,0,0,0],
                 'C': [0,30,0,20],
                 'D': [1,0,12,0],
                 }).set_index(['axis1'])

输出:

>>> df
         A  B   C   D
axis1                
Unix     3  1   0   1
Window   0  0  30   0
Apple    1  0   0  12
Linux   10  0  20   0

[4 rows x 4 columns]

所以基本上我想从存在值的数据透视表创建一个饼图,并使用“Unix A”等标签,其值为表中所有内容的 3/sum=%。

最佳答案

您可以使用 matplotlib 绘制饼图(例如参见 http://matplotlib.org/1.2.1/examples/pylab_examples/pie_demo.html )。

首先堆叠您的数据(以便不同的列成为索引级别,请参阅 stack docs ),然后仅选择正数:

In [13]: s = df.stack()

In [14]: s = s[s>0]

In [15]: s
Out[15]: 
axis1    
Unix    A     3
        B     1
        D     1
Window  C    30
Apple   A     1
        D    12
Linux   A    10
        C    20
dtype: int64

然后您可以使用 matplotlib pie 绘制此图(对于标签,我将索引的两个级别粘贴到列表理解中):

In [16]: fig, ax = plt.subplots()
    ...: ax.pie(s, labels=["{0} {1}".format(l1, l2) for l1, l2 in s.index], 
    ...:        autopct='%1.1f%%')

导致此输出: enter image description here

关于python-3.x - Python Pandas 将表格透视为饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22544342/

相关文章:

python - 如何向 python(矩阵)多维数组添加列?

python - 删除 pandas 数据框中的字符串

python - Pandas 时间序列多切片

python - 如何处理 Pandas 中的多值线终止符

python - MacOS 上的 Tkinter Python 3 缩放问题

Python matplotlib 在 Windows 7 上为 freetype、png 包安装问题

numpy - 在 Scipy 中计算 KL 散度时出错

python - 将嵌套字典中的键和值从列表格式获取到数据帧中

python-3.x - 属性错误 : module 'concurrent' has no attribute 'futures' when I try parallel processing in python 3. 6

python - 无法安装 OpenCV python3.8