【发布时间】:2021-04-03 03:59:06
【问题描述】:
所以我有一个包含多列的数据框,我正在使用此代码将数据框转换为 HTML 代码:
options_df = pd.DataFrame(data, columns=[
'Ticker', 'Type', 'Strike', 'Expiration', 'Filled', 'Current Premium', 'P/L', 'Date Signaled'])
html_str = '''
<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" href="df_styles.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
<body>
{options_table}
</body>
</html>.
'''
with open("index.html", "w") as options_f:
options_f.write(html_str.format(
options_table=options_df.to_html(classes='mystyle')))
这输出为:(仅出于长度目的显示第一行)
<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" href="df_styles.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
<body>
<table border="1" class="dataframe mystyle">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Ticker</th>
<th>Type</th>
<th>Strike</th>
<th>Expiration</th>
<th>Filled</th>
<th>Current Premium</th>
<th>P/L</th>
<th>Date Signaled</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>$OSTK</td>
<td>Call</td>
<td>90</td>
<td>2021-03-19</td>
<td>7.9</td>
<td>3.06</td>
<td>-484</td>
<td>2020-11-30</td>
</tr>
对于每一行中的第八列(即上面输出中读取 -484 的列),我想给它一个特定的 id 或类。有没有办法在 python 中使用 pandas dataframe.to_html() 来做到这一点,或者是否有另一个函数可以做到这一点?
如果不是,我要做的任务是根据其中的值是负数还是正数来改变第八列的背景颜色。我的想法是在 jQuery 中执行此操作,但没有特定的 id 或类,看起来我无法执行此操作。还有另一种方法可以做到这一点吗?谢谢!
【问题讨论】: