Python 使用CSS样式属性错误将dataframe(非唯一多索引)复制到html表

Python 使用CSS样式属性错误将dataframe(非唯一多索引)复制到html表,python,html,css,pandas,Python,Html,Css,Pandas,我正在尝试使用pandasStyle对象将pandas数据框导出到带有自定义CSS着色选项的html表中。我已经通读了下面列出的例子: 我知道我需要创建一个样式对象,然后渲染该对象 我的问题是我的特定表引发了一个异常:AttributeError:'str'对象没有属性“ndim”。我的表与链接中的示例表不同,因为它包含一个非唯一的多索引 使用此代码可以创建此ValueError的最简单示例: import pandas as pd import numpy as np myTable =

我正在尝试使用pandas
Style
对象将pandas数据框导出到带有自定义CSS着色选项的html表中。我已经通读了下面列出的例子:

我知道我需要创建一个样式对象,然后渲染该对象

我的问题是我的特定表引发了一个异常:
AttributeError:'str'对象没有属性“ndim”
。我的表与链接中的示例表不同,因为它包含一个非唯一的多索引

使用此代码可以创建此
ValueError
的最简单示例:

import pandas as pd
import numpy as np



myTable = pd.DataFrame({ 'Class': ['A', 'A', 'A', 'A', 'A'],
                    'First' : ['John', 'Lenny', 'Bill', 'Ryan', 'James'],
                    'Last': ['McGee', 'Beir', 'Schwarts', 'Mulroney', 'Buchura'],
                    'Grade': [76, 87, 46, 83, 98],
                    'StudentID': [2828, 2673, 7811, 2828, 1782]})

myTable.set_index(['Class', 'StudentID'], inplace=True)
myTable = myTable[['First', 'Last', 'Grade']] 

s = myTable.style

html = s.render()

text_file = open('df.html', "w")
text_file.write(s)
text_file.close()
请注意,该表包含一个非唯一索引(第1行和第4行)

此外,如果我去掉非唯一性,则会引发另一个异常:
AttributeError:'str'对象没有属性“ndim”
。下面的示例将产生该错误:

import pandas as pd
import numpy as np



myTable = pd.DataFrame({ 'Class': ['A', 'A', 'A', 'A', 'A'],
                    'First' : ['John', 'Lenny', 'Bill', 'Ryan', 'James'],
                    'Last': ['McGee', 'Beir', 'Schwarts', 'Mulroney', 'Buchura'],
                    'Grade': [76, 87, 46, 83, 98],
                    'StudentID': [2828, 2673, 7811, 2878, 1782]})

myTable.set_index(['Class', 'StudentID'], inplace=True)
myTable = myTable[['First', 'Last', 'Grade']] 

s = myTable.style

html = s.render()

text_file = open('df.html', "w")
text_file.write(s)
text_file.close()

如何避免这些错误?为什么熊猫会将样式选项限制为唯一的一维索引
DataFrames

这不起作用的原因是,当您使用并将其更改为HTML时,您会看到创建了额外的空标题和多个标题行

样式不是为多重索引编写的。您可能需要替换呈现HTML中的数据,而不是使用熊猫样式

你也没有什么风格。。。你确定不只是需要添加.to_html()吗

选择2 我也看到了类似的东西,建议使用

选择3 更改CSS样式

在HTML的开头,您可以添加如下内容:

<style>
table {text-align: center;}
table thead th {text-align: center;}
</style>

表{文本对齐:居中;}
表THAD{text align:center;}

我无法重现第二个示例中的错误。@Tedperou奇怪,您使用的是Python 3.5吗?第一个错误呢?
<style>
table {text-align: center;}
table thead th {text-align: center;}
</style>