使用pandas.to_html时怎么自定义表格样式

一、通过标签名设置css样式

使用pd.to_html()方法如果不指定文件路径,该函数会返回一个格式化的html字符串,我们可以对这个字符串进行自定义操作,比如直接用我们设置的css样式加上这个格式化的html,就可以实现自定义表格样式,如下:

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式将DataFrame转换为HTML
custom_css = """
<style>
table {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
table th, table td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)

效果如下:

二、通过class选择器设置css样式

pd.to_html()方法生成html字符串时会自动添加一个名为dataframeclass类选择器,如下:

<table border="1" class="dataframe">
  <thead>...</thead>
  <tbody>...</tbody>
</table>

使用默认类选择器设置样式

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式
custom_css = """
<style>
.dataframe {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
.dataframe th, .dataframe td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# # 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)

使用自定义类选择器设置样式

需要指定参数classes,该参数会在html代码中自动添加一个class类选择器,如下:

df.to_html(classes="custom-table")
<table border="1" class="dataframe custom-table">
  <thead>...</thead>
  <tbody>...</tbody>
</table>

如此就可以通过自定义类名实现样式设置,如下示例:

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式将DataFrame转换为HTML
custom_css = """
<style>
.custom-table {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
.custom-table th, .custom-table td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(classes="custom-table", index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# # 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)
# -*- coding: utf-8 -*- import pandas as pd from pyecharts import options as opts from pyecharts.charts import Line,Bar,Funnel,Pie from pyecharts.components import Table from pyecharts.options import ComponentTitleOpts from sqlalchemy import create_engine from pyecharts.charts import Page from pyecharts.charts import WordCloud from collections import Counter import jieba import re # 创建数据库连接 engine = create_engine('mysql+pymysql://root:123456@localhost/doubandata') #1. #2. def line_chart2(): # 从数据库中读取数据 query = "SELECT show_time FROM t_music" df = pd.read_sql(query, engine) # 处理日期数据,提取年份 df['year'] = pd.to_datetime(df['show_time'], errors='coerce').dt.year # 统计每年的歌曲发行数量 year_counts = df['year'].dropna().astype(int).value_counts().sort_index() # 准备数据用于生成折线图 years = year_counts.index.astype(str).tolist() counts = year_counts.values.tolist() # 创建折线图 line = Line(init_opts=opts.InitOpts(width="1600px", height="800px")) line.add_xaxis(years) line.add_yaxis("歌曲发行数量", counts, label_opts=opts.LabelOpts(is_show=True, position="top")) # 设置全局配置项 line.set_global_opts( title_opts=opts.TitleOpts(title="每年歌曲发行数量统计"), xaxis_opts=opts.AxisOpts(type_="category", name="年份"), yaxis_opts=opts.AxisOpts(type_="value", name="发行数量"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross") ) # 渲染图表到HTML文件 line.render("2.song_release_counts_by_year.html") return line #3. def line_chart3(): # 从数据库中读取数据 query = "SELECT show_time, score FROM t_music" df = pd.read_sql(query, engine) # 将 score 列转换为数值类型,无法转换的会变为 NaN df['score'] = pd.to_numeric(df['score'], errors='coerce') # 处理日期数据,提取年份 df['year'] = pd.to_datetime(df['show_time'], errors='coerce').dt.year # 删除无效数据(如日期或评分为空) df = df.dropna(subset=['year', 'score']) # 按年份分组并计算每年的平均评分,保留一位小数 yearly_avg_scores = df.groupby('year')['score'].mean().round(1).sort_index() # 准备数据用于生成折线图 years = yearly_avg_scores.index.astype(int).astype(str).tolist() # 确保年份为整数且不带小数点 avg_scores = yearly_avg_scores.values.tolist() # 创建折线图 line = Line(init_opts=opts.InitOpts(width="1600px", height="800px")) line.add_xaxis(years) line.add_yaxis("平均评分", avg_scores, label_opts=opts.LabelOpts(is_show=True, position="top")) # 设置全局配置项 line.set_global_opts( title_opts=opts.TitleOpts(title="每年歌曲发行的平均评分"), xaxis_opts=opts.AxisOpts(type_="category", name="年份"), yaxis_opts=opts.AxisOpts(type_="value", name="平均评分", min_=7, max_=10), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross") ) # 渲染图表到 HTML 文件 line.render("3.song_release_scores_by_year.html") return line page = Page( page_title="基于Python的豆瓣音乐数据分析与可视化", layout=Page.DraggablePageLayout, # 拖拽方式 ) page.add_js_funcs( """ document.body.style.backgroundColor = '#f0f8ff'; // 设置背景颜色为淡蓝色 """ ) # 添加图表到页面 page.add( # 绘制折线图 line_chart2(), line_chart3(), # 绘制表格 ) # 渲染大屏到临HTML文件 page.render('大屏_临1.html') 怎么生成好看个性化的可视化大屏网页
03-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值