pandas style
pandas 提供了DataFrame.style属性, 返回Styler对象, 用于数据样式的美化
- Styler.applymap 作用于DataFrame中所有元素
- Styler.apply 用于行, 列 或整个表
# 数据源
ID NAME COURSE SCORE
1 小明 ENG 10
2 小红 ENG 66
3 小李 MATH 88
4 小张 MATH 100
5 老王 MATH 69
例子
高亮显示
# 将最高成绩背景色标黄
import pandas as pd
df = pd.read_excel(r'score.xlsx')
def highlight(x):
is_max = x == x.max()
# print(is_max)
return ['background-color:yellow' if i else '' for i in is_max]
# return ['', '', '', 'background-color:yellow', '']
df.style.apply(highlight,subset=['SCORE']).to_excel('color.xlsx',index=None)
# 大于60分的字体变绿
def color_green(x):
is_max = x > 60
return ['color:green' if i else '' for i in is_max]
df.style.apply(color_green,subset=['SCORE']).to_excel('color.xlsx',index=None)