表格視覺(jué)樣式:Dataframe.style → 返回pandas.Styler對(duì)象的屬性艾岂,具有格式化和顯示Dataframe的有用方法
樣式創(chuàng)建:
① 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(6,4),columns=['a','b','c','d'])
sty = df.style
print(sty,type(sty))
# 查看樣式類(lèi)型
sty
# 顯示樣式
# 按元素處理樣式:style.applymap()
def color_neg_red(val):
if val < 0:
color = 'red'
else:
color = 'black'
return('color:%s' % color)
df.style.applymap(color_neg_red)
# 創(chuàng)建樣式方法红且,使得小于0的數(shù)變成紅色
# style.applymap() → 自動(dòng)調(diào)用其中的函數(shù)
# print(color_neg_red,type(color_neg_red))
# 按行/列處理樣式:style.apply()
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'])
# 創(chuàng)建樣式方法,每列最大值填充黃色
# axis:0為列敏晤,1為行,默認(rèn)為0
# subset:索引
# 樣式索引株搔、切片
df.style.apply(highlight_max, axis = 1,
subset = pd.IndexSlice[2:5,['b', 'd']])
# 通過(guò)pd.IndexSlice[]調(diào)用切片
# 也可:df[2:5].style.apply(highlight_max, subset = ['b', 'd']) → 先索引行再做樣式
表格顯示控制
df.style.format()
# 按照百分?jǐn)?shù)顯示
df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d'])
print(df.head())
df.head().style.format("{:.2%}")
# 顯示小數(shù)點(diǎn)數(shù)
df.head().style.format("{:.4f}")
# 顯示正負(fù)數(shù)
df.head().style.format("{:+.2f}")
# 分列顯示
df.head().style.format({'b':"{:.2%}", 'c':"{:+.3f}", 'd':"{:.3f}"})
表格樣式調(diào)用
Styler內(nèi)置樣式調(diào)用
# 定位空值
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 =0,low=1,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:最長(zhǎng)長(zhǎng)度在格子的占比
# 分段式構(gòu)建樣式
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')