Travel Tips
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
表格视觉样式:Dataframe.style → 返回pandas.Styler对象的属性,具有格式化和显示Dataframe的有用方法 样式创建: ① Styler.applymap:elementwise → 按元素方式处理Dataframe ② Styler.apply:column- / row- / table-wise → 按行/列处理Dataframe
表格视觉样式:Dataframe.style → 返回pandas.Styler对象的属性,具有格式化和显示Dataframe的有用方法
样式创建:
① Styler.applymap:elementwise → 按元素方式处理Dataframe
② Styler.apply:column- / row- / table-wise → 按行/列处理Dataframe
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline
df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d']) sty = df.style print(sty,type(sty)) # 查看样式类型 sty # 显示样式
def color_neg_red(val): if val < 0: color = 'red' else: color = 'black' return('color:%s' % color) df.style.applymap(color_neg_red) # val 为40个值 # 创建样式方法,使得小于0的数变成红色 # style.applymap() → 自动调用其中的函数
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 = ['b','c']) # 创建样式方法,每列最大值填充黄色 # axis:0为列,1为行,默认为0 # subset:索引
df.style.apply(highlight_max, axis = 1, subset = pd.IndexSlice[2:5,['b', 'd']]) # 通过pd.IndexSlice[]调用切片 # 也可:df[2:5].style.apply(highlight_max, subset = ['b', 'd']) → 先索引行再做样式
df.style.format()
df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d']) print(df.head()) df.head().style.format("{:.2%}")
df.head().style.format("{:.4f}")
df.head().style.format("{:+.2f}")
df.head().style.format({'b':"{:.2%}", 'c':"{:+.3f}", 'd':"{:.3f}"})
Styler内置样式调用
df = pd.DataFrame(np.random.rand(5,4),columns = list('ABCD')) df['A'][2] = np.nan df.style.highlight_null(null_color='red')
df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD')) df.style.background_gradient(cmap='Greens',axis =1,low=0,high=1) # cmap:颜色 # axis:映射参考,0为行,1以列
df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD')) df.style.bar(subset=['A', 'B'], color='#d65f5f', width=100) # width:最长长度在格子的占比
df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD')) df['A'][[3,2]] = np.nan df.style.\ bar(subset=['A', 'B'], color='#d65f5f', width=100).\ highlight_null(null_color='yellow')
Sed ac lorem felis. Ut in odio lorem. Quisque magna dui, maximus ut commodo sed, vestibulum ac nibh. Aenean a tortor in sem tempus auctor
December 4, 2020 at 3:12 pm
Sed ac lorem felis. Ut in odio lorem. Quisque magna dui, maximus ut commodo sed, vestibulum ac nibh. Aenean a tortor in sem tempus auctor
December 4, 2020 at 3:12 pm
Donec in ullamcorper quam. Aenean vel nibh eu magna gravida fermentum. Praesent eget nisi pulvinar, sollicitudin eros vitae, tristique odio.
December 4, 2020 at 3:12 pm
我是 s enim interduante quis metus. Duis porta ornare nulla ut bibendum
Rosie
6 minutes ago