【问题标题】:Is it possible to add a class or id to a specific column <td> when using python pandas dataframe.to_html()使用 python pandas dataframe.to_html() 时是否可以将类或 id 添加到特定列 <td>
【发布时间】: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 或类,看起来我无法执行此操作。还有另一种方法可以做到这一点吗?谢谢!

【问题讨论】:

    标签: python html jquery pandas


    【解决方案1】:

    一个快速而简单的选项是处理 df.to_html() 返回的字符串。例如:

    data = [
        ['K1', 1],
        ['K2', -1],
    ]
    
    df = pd.DataFrame(data, columns=['key', 'value'])
    
    m_positive = df['value'] > 0
    df.loc[m_positive, 'value'] = '__positive__' + df.loc[m_positive, 'value'].astype(str)
    df.loc[~m_positive, 'value'] = '__negative__' + df.loc[~m_positive, 'value'].astype(str)
    
    def updateRowStyle(line):
        return line.replace('>__positive__', ' class = "positive">').replace('>__negative__', ' class="negative">')
    
    result =list(map(updateRowStyle, df.to_html().split('\n')))
    
    for line in result:
        print(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-30
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多