繁体   English   中英

带有CSS样式属性错误的Pandas数据框(非唯一多索引)到html表

[英]Pandas dataframe (non-unique multi-index) to html table with CSS styling attribute error

我正在尝试使用pandas Style对象将pandas数据帧导出到具有自定义CSS着色选项的html表中。 我已阅读了以下示例: http : //pandas.pydata.org/pandas-docs/stable/style.html

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

我的问题是我的特定表引发了一个异常: AttributeError: 'str' object has no attribute '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()

请注意,该表包含一个非唯一索引(第一行和第四行)。

而且,如果我摆脱了非唯一性,则会引发另一个异常: AttributeError: 'str' object has no attribute '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

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

没有为MultiIndexing编写样式。 您可能需要替换呈现的HTML中的数据,而不是使用pandas样式。

您也没有任何样式可言...您确定不只是需要添加.to_html()吗?

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']] 

html = myTable.to_html()

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

选项2

我也看到了这篇类似文章 ,建议使用pd.IndexSlice

选项3

更改CSS样式

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM