看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)给定学生成绩数据表,要求使用pandas样式功能对表格进行统一的样式美化。源数据如下:
import pandas as pd
data = {
'学号': ['S001', 'S002', 'S003', 'S004'],
'姓名': ['张三', '李四', '王五', '赵六'],
'数学': [90, 75, 85, 88],
'语文': [85, 92, 78, 90],
'英语': [95, 80, 85, 92],
'总分': [270, 247, 248, 270]
}
df = pd.DataFrame(data)
df
输出结果:
学号 姓名 数学 语文 英语 总分
0 S001 张三 90 85 95 270
1 S002 李四 75 92 80 247
2 S003 王五 85 78 85 248
3 S004 赵六 88 90 92 270
具体要求:
代码如下:
(df.style
.set_properties(**{'font-size': '12px', 'text-align': 'center'})
.set_properties(subset=pd.IndexSlice[:, ['数学', '语文', '英语', '总分']],
**{'background-color': '#f0f0f0'})
.set_table_styles([{
'selector': 'th',
'props': [('background-color', '#2c3e50'),
('color', 'white'),
('font-weight', 'bold')]
}])
)
输出结果:(生成带有以下样式的表格)
参考代码采用链式调用方式,通过set_properties()实现批量样式设置:
关键技巧:set_properties()支持批量设置CSS属性,subset参数可以精确控制应用范围,结合set_table_styles()可以实现表格各部分的差异化样式设计。
(完)
更新时间:2025-09-21 09:01:29 标签:pandas python 样式 批量设置