首页 > 解决方案 > 带有单个标题行的 pandas 中的 HTML 表格

问题描述

我有以下数据框:

 ID     mutex add  atomic add  cas add  ys_add  blocking ticket  queued fifo
Cores                                                                      
1           21.0         7.1     12.1     9.8             32.2         44.6
2          121.8        40.0    119.2   928.7           7329.9       7460.1
3          160.5        81.5    227.9  1640.9          14371.8      11802.1
4          188.9       115.7    347.6  1945.1          29130.5      15660.1 

有列索引 ( ID) 和行索引 ( Cores)。当我使用 时DataFrame.to_html(),我得到一个像这样的表:

实际的

相反,我想要一个具有单个标题行的表,由所有列名(但没有列索引名称ID)和Cores同一标题行中的行索引名称组成,如下所示:

期望的

我愿意在to_html()调用之前操作数据帧,或者在调用中添加参数to_html(),但不会弄乱生成的html.

标签: pythonpandasdataframe

解决方案


最初设定:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],
                 columns = ['attr_a', 'attr_b', 'attr_c', 'attr_c'])

df.columns.name = 'ID'
df.index.name = 'Cores'
df

ID  attr_a  attr_b  attr_c  attr_c
Cores               
0        1       2       3       4
1        5       6       7       8
2        9      10      11      12
3       13      14      15      16

然后将 columns.name 设置为“Cores”,将 index.name 设置为 None。df.to_html() 然后应该给你你想要的输出。

df.columns.name='Cores'
df.index.name = None
df.to_html()


Cores   attr_a  attr_b  attr_c  attr_c
0            1       2       3       4
1            5       6       7       8
2            9      10      11      12
3           13      14      15      16

推荐阅读