Python将dataframe转换为html,根据标题值高亮显示整个列

2024-06-06 23:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe(从字典中提取),它将当前一周的工作日作为列标题,在行中填充人名

dict = {'2019-03-25': ['Bob', '', 'Joe'], '2019-03-26': ['Abel', '', ''], '2019-03-27': ['', '', ''], '2019-03-28': ['', 'Bob', ''], '2019-03-29': ['Richard', 'Joe', 'Fred']}

df = pd.DataFrame(data=dict)

currentdate = datetime.datetime.today().strftime('%Y-%m-%d')

我想突出显示整个列中column header=currentdate的所有单元格,然后将其转换为html

我看了其他地方,认为这是一个独特的场景,因为我在网上能找到的只是基于单元格本身的值高亮显示,例如值大于或小于或包含特定文本,但与列标题本身的值无关。你知道吗

编辑: 基本上我在excel中有一个日历,我把它拉到一个数据框中,然后将它转换成HTML并作为电子邮件发送出去。下面是我得到的结果(减去亮点)。我想创建一个if语句来格式化html,以便在header==current date时突出显示黄色列。你知道吗

enter image description here


Tags: richard标题dataframedfdatetime字典htmlfred
1条回答
网友
1楼 · 发布于 2024-06-06 23:18:21

请注意,将数据保留为列名并不是一种很好的做法。在本例中,这意味着日期记录。这也使得代码更加复杂。你知道吗

试试这个代码片段,我已经添加了注释。你知道吗

import pandas as pd

# note that I've replaced '' with None
d = {'2019-04-30': ['Bob', None, 'Joe'], '2019-03-26': ['Abel', None, None], '2019-03-27': [None, None, None], '2019-03-28': [None, 'Bob', None], '2019-03-29': ['Richard', 'Joe', 'Fred']}

# load items of dictionary as dataframe, don't use dates as column names, assign column names
df = pd.DataFrame(data=d.items(), columns = ['date','name_list'])

# convert string to datetime
# it's better to compare datetimes directly, and forces the type to datetime, in case of dirty data
# also using pandas datetime instead of the standard python library
df.date = pd.to_datetime(df.date)

# this is your filter or 'where' clause, to keep only records that match today
df = df.loc[df['date'] == pd.to_datetime('today')]

# unpack list as individual rows, see https://stackoverflow.com/a/12681217/2327328
df = pd.concat([pd.Series(row['date'], row['name_list'])              
                for _, row in df.iterrows()]).reset_index()


# display as html
print (df.to_html())

作为输出提供:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>index</th>
      <th>0</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Bob</td>
      <td>2019-04-30</td>
    </tr>
    <tr>
      <th>1</th>
      <td>None</td>
      <td>2019-04-30</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Joe</td>
      <td>2019-04-30</td>
    </tr>
  </tbody>
</table>

显示如下:

enter image description here

相关问题 更多 >