gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:45:37 31 4
gpt4 key购买 nike

我正在尝试使用 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()

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

此外,如果我摆脱非唯一性,则会引发另一个异常: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()

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

最佳答案

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

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

你也没有任何样式......你确定你不需要添加 .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

我还看到了this post对于类似的东西,建议使用 pd.IndexSlice

选项 3

改变你的 CSS 样式

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

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

关于python - 带有 CSS 样式属性错误的 Pandas 数据框(非唯一多索引)到 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41702417/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com