【问题标题】:While plotting pandas pivot table headers and sub-headers got merged in python/pandas在绘制 pandas 数据透视表标题和子标题时合并到 python/pandas
【发布时间】:2020-06-25 00:42:52
【问题描述】:

下面是数据库,然后编码然后输出,它有标题(价格)和子标题(CPU,维护和软件)

Rep             Manager         Product     Quantity    Price       Status
Craig Booker    Debra Henley    CPU         1           30000.125   Presented
Craig Booker    Debra Henley    Software    1           10000.340   Presented
Craig Booker    Debra Henley    Maintenance 2           5000.359    Pending
Craig Booker    Debra Henley    CPU         1           35000.679   Declined
Daniel Hilton   Debra Henley    CPU         2           65000.000   Won
Cedric Moss     Fred Anderson   Software    3           27500.000   Presented
Wendy Yule      Fred Anderson   Maintenance 4           44250.000   Won

    import pandas as pd
    from pandas.plotting import table
    import numpy as np
    import matplotlib.pyplot as plt
    df=pd.read_excel('Book1.xlsx')
    df
    df=df.pivot_table(df,index=['Manager','Status'],columns=['Product'],aggfunc={'Price':np.sum,'Quantity':len},fill_value='-',margins=False)
    df

但是当我在一个带有下面编码标题和子标题的图中绘制时,它们被合并到一个单元格中。请问如何避免这种情况?

fig=plt.figure(figsize=(15,10))
ax=plt.subplot(111,frame_on=False)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
tb1=table(ax,df,loc='center',colWidths=[0.15, 0.24, 0.2,0.2,0.25,0.22])
tb1.set_fontsize(17)
tb1.scale(1,7)
plt.show()

*我希望价格和数量位于顶部,带有子标题(CPU、维护和软件),如第一张图片所示。

谢谢*

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:

    根据this answerpandas.tools.plotting.table 不支持multiIndex,因此它会在遍历数据框的列和行时返回一个元组。枢轴导致您的数据框具有 both 列和索引类型为multiIndex,这会导致当您尝试绘制数据框时所有“子标题”都被放入元组中。据我所知,没有解决方法。

    获取所需表格的一种方法是使用df.to_html().replace('\n', '') 将 html 代码生成为长字符串(没有任何“\n”)。

    html 表格的默认设置相当难看,因此我添加了一些 CSS 以使格式更接近您想要的输出表格 - 随意添加更多更改以改进格式。

    tr:nth-child(even) {background-color: #f2f2f2;}
    
    td {
      border: None;
      text-align: right;
      padding: 5px;
    }
    
    th {
      border: None;
      text-align: center;
      padding: 5px;
    }
    <table border="1" class="dataframe">
      <thead>
        <tr>
          <th></th>
          <th></th>
          <th colspan="3" halign="left">Price</th>
          <th colspan="3" halign="left">Quantity</th>
        </tr>
        <tr>
          <th></th>
          <th>Product</th>
          <th>CPU</th>
          <th>Maintenance</th>
          <th>Software</th>
          <th>CPU</th>
          <th>Maintenance</th>
          <th>Software</th>
        </tr>
        <tr>
          <th>Manager</th>
          <th>Status</th>
          <th></th>
          <th></th>
          <th></th>
          <th></th>
          <th></th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th rowspan="4" valign="top">Debra Henley</th>
          <th>Declined</th>
          <td>35000.7</td>
          <td>-</td>
          <td>-</td>
          <td>1</td>
          <td>-</td>
          <td>-</td>
        </tr>
        <tr>
          <th>Pending</th>
          <td>-</td>
          <td>5000.36</td>
          <td>-</td>
          <td>-</td>
          <td>1</td>
          <td>-</td>
        </tr>
        <tr>
          <th>Presented</th>
          <td>30000.1</td>
          <td>-</td>
          <td>10000.3</td>
          <td>1</td>
          <td>-</td>
          <td>1</td>
        </tr>
        <tr>
          <th>Won</th>
          <td>65000</td>
          <td>-</td>
          <td>-</td>
          <td>1</td>
          <td>-</td>
          <td>-</td>
        </tr>
        <tr>
          <th rowspan="2" valign="top">Fred Anderson</th>
          <th>Presented</th>
          <td>-</td>
          <td>-</td>
          <td>27500</td>
          <td>-</td>
          <td>-</td>
          <td>1</td>
        </tr>
        <tr>
          <th>Won</th>
          <td>-</td>
          <td>44250</td>
          <td>-</td>
          <td>-</td>
          <td>1</td>
          <td>-</td>
        </tr>
      </tbody>
    </table>

    要同时使用 python 和 html,请创建一个 jupyter notebook(有很多关于如何做到这一点的教程,但使用 google colab 很简单),并在你的 python 代码之后包含 import 语句:

    import pandas as pd
    from pandas.plotting import table
    import numpy as np
    import matplotlib.pyplot as plt
    df=pd.read_excel('Book1.xlsx')
    df
    df=df.pivot_table(df,index=['Manager','Status'],columns=['Product'],aggfunc={'Price':np.sum,'Quantity':len},fill_value='-',margins=False)
    df
    html_table_string = df.to_html().replace('\n', '')
    
    from IPython.display import HTML, display
    HTML("""
    <style>
    // add the above or your own CSS styling here
    </style>
    """)
    display(HTML(html_table_string)
    

    【讨论】:

    • 除了 (pandas.tools.plotting.table) 之外还有什么其他方法可以用来获得所需的格式吗?
    • 更新了我的答案。如果您已经在使用 Jupyter 笔记本,则只需将上述代码复制并粘贴到下一个单元格中即可。如果没有,那么 Google Colab:colab.research.google.com/notebooks/welcome.ipynb 是一个不错的起点。您可以创建一个新笔记本,并根据需要上传您的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2018-01-31
    • 2020-04-24
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多