gpt4 book ai didi

python - 我可以在 pandas 数据框的列标签上方添加标题/标题行并将其输出为 HTML 吗?

转载 作者:行者123 更新时间:2023-12-01 07:12:08 27 4
gpt4 key购买 nike

根据下面的示例,我将数据帧输出到电子邮件正文。是否可以在列标签行上方添加标题行或标题行?最好是一行是一个单元格,数据帧的长度,包含一个字符串?

import pandas as pd
import numpy as np
from IPython.core.display import display, HTML

dates = pd.date_range('20130101',periods=3)
df = pd.DataFrame(np.random.randn(3,4),index=dates,columns=list('ABCD'))

styles = [{'props':[("font-family", "Calibri")]}, {
'selector': 'th',
'props': [
('background-color', 'yellow')]}]
s = df.style.set_table_styles(styles)

html = s.hide_index().render()
with open("html_c.html","w") as fp:
fp.write(html)
#to display in a jupyter notebook
display(HTML(html))

当前输出:

enter image description here

期望的输出:

enter image description here

最佳答案

也许是这样的?

import pandas as pd
import numpy as np
from IPython.core.display import display, HTML

dates = pd.date_range('20130101',periods=3)

### >>> begin
columns = list("ABCD")
columns = list(zip(['HEADER'] * 4, columns))
#[('HEADER', 'A'), ('HEADER', 'B'), ('HEADER', 'C'), ('HEADER', 'D')]
columns = pd.MultiIndex.from_tuples(columns, names=['first', 'second'])
### >>> end

df = pd.DataFrame(np.random.randn(3,4),index=dates,columns=columns) # <--- also here
styles = [{'props':[("font-family", "Calibri")]}, {
'selector': 'th',
'props': [
('background-color', 'yellow'),
('text-align','center')] # for alignment
}]
s = df.style.set_table_styles(styles)

html = s.hide_index().render()
with open("html_c.html","w") as fp:
fp.write(html)
#to display in a jupyter notebook
display(HTML(html))

enter image description here

关于python - 我可以在 pandas 数据框的列标签上方添加标题/标题行并将其输出为 HTML 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151715/

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