1、有Dataframe创建表格样式
import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.random.randn(5,3),columns=['one','two','three']) sty = df.style sty2、表格元素处理
a、按元素处理样式
def color_neg_red(val): if val < 0: color = 'red' else: color = 'black' return('color:%s' % color) df.style.applymap(color_neg_red) # style.applymap() → 自动调用其中的函数
b、按行/列处理样式
def highlight_max(s): is_max = s == s.max() #print(is_max) lst = [] for v in is_max: if v: lst.append('background-color: yellow') else: lst.append('') return(lst) df.style.apply(highlight_max, axis = 0, subset = ['one','two']) # axis:0为列,1为行,默认为0 # subset:索引3、样式索引、切片
df.style.apply(highlight_max, axis = 1, subset = pd.IndexSlice[['one', 'two']]) # 通过pd.IndexSlice[]调用切片 # 也可以写成:df[0:3].style.apply(highlight_max, subset = ['one', 'two']) # 先索引行再做样式