Python 使用 to_html 将 CSS 类应用于 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50807744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:36:22  来源:igfitidea点击:

Apply CSS class to Pandas DataFrame using to_html

pythonpandasdataframe

提问by sparrow

I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.

我在使用 Pandas 的“to_html”方法应用“classes”参数来设置 DataFrame 样式时遇到问题。

"classes : str or list or tuple, default None CSS class(es) to apply to the resulting html table" from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

"classes : str or list or tuple, default None CSS class(es) to apply to the result html table" from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html。 html

I am able to render a styled DataFrame like this (for example):

我能够渲染这样的样式数据帧(例如):

df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
    f.write(myhtml)        

How can I style html output from a DataFrame using "classes" with "to_html" like this:

如何使用带有“to_html”的“类”来设置来自 DataFrame 的 html 输出的样式,如下所示:

df.to_html('myhtml.html',classes=<something here>)

回答by Parfait

Pandas' to_htmlsimply outputs a large string containing HTML table markup. The classes argument is a convenience handler to give the <table>a classattribute that will be referenced in a previously createdCSS document that styles it. Therefore, incorporate to_htmlinto a wider HTML document build that references an external CSS.

Pandasto_html只是输出一个包含 HTML 表格标记的大字符串。classes 参数是一个方便的处理程序,用于提供<table>一个class属性,该属性将在先前创建的CSS 文档中引用它的样式。因此,合并to_html到引用外部 CSS 的更广泛的 HTML 文档构建中。

Interestingly, to_htmladds dual classes <table class="dataframe mystyle">which can be referenced in CSS individually, .dataframe {...} .mystyle{...}, or together .dataframe.mystyle {...}. Below demonstrates with random data.

有趣的是,to_html添加了<table class="dataframe mystyle">可以在 CSS 中单独.dataframe {...} .mystyle{...}、或一起引用的双类.dataframe.mystyle {...}。下面用随机数据演示。

Data

数据

import pandas as pd
import numpy as np

pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')

np.random.seed(6182018)
demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
                        'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50),              
                        'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50), 
                        'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50), 
                        'num1': np.random.randn(50)*100,
                        'num2': np.random.uniform(0,1,50),                   
                        'num3': np.random.randint(100, size=50),
                        'bool': np.random.choice([True, False], 50)
                       },
                        columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
          )


print(demo_df.head(10))
#      date    analysis_tool     num1      database     num2        os      num3  bool 
# 0 2018-04-21     pandas     153.474246       mysql  0.658533         ios   74    True
# 1 2018-04-13        sas     199.461669      sqlite  0.656985   windows 7   11   False
# 2 2018-06-09      stata      12.918608      oracle  0.495707     android   25   False
# 3 2018-04-24       spss      88.562111  sql server  0.113580   windows 7   42   False
# 4 2018-05-05       spss     110.231277      oracle  0.660977  windows 10   76    True
# 5 2018-04-05        sas     -68.140295  sql server  0.346894  windows 10    0    True
# 6 2018-05-07      julia      12.874660    postgres  0.195217         ios   79    True
# 7 2018-01-22          r     189.410928       mysql  0.234815  windows 10   56   False
# 8 2018-01-12     pandas    -111.412564  sql server  0.580253      debian   30   False
# 9 2018-04-12          r      38.963967    postgres  0.266604   windows 7   46   False

CSS(save as df_style.css)

CSS (另存为 df_style.css)

/* includes alternating gray and white with on-hover color */

.mystyle {
    font-size: 11pt; 
    font-family: Arial;
    border-collapse: collapse; 
    border: 1px solid silver;

}

.mystyle td, th {
    padding: 5px;
}

.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}

.mystyle tr:hover {
    background: silver;
    cursor: pointer;
}

Pandas

熊猫

pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>

html_string = '''
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    {table}
  </body>
</html>.
'''

# OUTPUT AN HTML FILE
with open('myhtml.html', 'w') as f:
    f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))


OUTPUT

输出

HTML(references df_style.css, assumed in same directory; see class argument in table)

HTML (引用 df_style.css,假定在同一目录中;请参阅表中的类参数)

<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    <table border="1" class="dataframe mystyle">
  <thead>
    <tr style="text-align: center;">
      <th></th>
      <th>date</th>
      <th>analysis_tool</th>
      <th>num1</th>
      <th>database</th>
      <th>num2</th>
      <th>os</th>
      <th>num3</th>
      <th>bool</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>2018-04-21</td>
      <td>pandas</td>
      <td>153.474246</td>
      <td>mysql</td>
      <td>0.658533</td>
      <td>ios</td>
      <td>74</td>
      <td>True</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2018-04-13</td>
      <td>sas</td>
      <td>199.461669</td>
      <td>sqlite</td>
      <td>0.656985</td>
      <td>windows 7</td>
      <td>11</td>
      <td>False</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2018-06-09</td>
      <td>stata</td>
      <td>12.918608</td>
      <td>oracle</td>
      <td>0.495707</td>
      <td>android</td>
      <td>25</td>
      <td>False</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2018-04-24</td>
      <td>spss</td>
      <td>88.562111</td>
      <td>sql server</td>
      <td>0.113580</td>
      <td>windows 7</td>
      <td>42</td>
      <td>False</td>
    </tr>
    <tr>
      <th>4</th>
      <td>2018-05-05</td>
      <td>spss</td>
      <td>110.231277</td>
      <td>oracle</td>
      <td>0.660977</td>
      <td>windows 10</td>
      <td>76</td>
      <td>True</td>
    </tr>
    ...
  </tbody>
</table>
  </body>
</html>

HTML Output

HTML 输出

回答by Shubham Chourasia

Here's how I did it

这是我如何做到的

Create a text file for css code and write down your css code here, say css_style.txt Now read this txt file as a string in your python file

为 css 代码创建一个文本文件并在这里​​写下你的 css 代码,比如 css_style.txt 现在将这个 txt 文件作为你的 python 文件中的字符串读取

with open('css_style.txt', 'r') as myfile: style = myfile.read()

with open('css_style.txt', 'r') as myfile: style = myfile.read()

Now in HTML code

现在在 HTML 代码中

"""<html><head>Something Something</head>{1}<div>{0}</div></html>""".format(some_panda_dataframe.to_html,style)

Here in my case css_style.txt file is

在我的例子中 css_style.txt 文件是

<style>
table {
  border-collapse: collapse;
  width: 100%;
}

th {
  text-align: center;
  padding: 8px;
}

td {
  text-align: left;
  padding: 8px;
}

tr:nth-child(even){background-color: #FFD5D5}

th {
  background-color: #0000FF;
  color: white;
}
</style>

回答by hui chen

Essentially, the pandas.to_html() just exports a plain HTML table. You can insert the table wherever you want in the body and control the style via CSS in the style section.

本质上,pandas.to_html() 只是导出一个普通的 HTML 表格。您可以在正文中的任何位置插入表格,并通过样式部分中的 CSS 控制样式。

<html>
<head>
<style> 
  table, th, td {{font-size:10pt; border:1px solid black; border-collapse:collapse; text-align:left;}}
  th, td {{padding: 5px;}}
</style>
</head>
<body>
{
  pandas.to_html()
}
</body>
</html>