【課程3.13】 表格樣式創建
表格視覺樣式:Dataframe.style → 返回pandas.Styler對象的屬性,具有格式化和顯示Dataframe的有用方法
樣式創建:
① Styler.applymap:elementwise → 按元素方式處理Dataframe
② Styler.apply:column- / row- / table-wise → 按行/列處理Dataframe
1.樣式
df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d'])
sty = df.style
print(sty,type(sty))
# 查看樣式類型
sty
# 顯示樣式
2.按元素處理樣式: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)
# 創建樣式方法,使得小於0的數變成紅色
# style.applymap() → 自動調用其中的函數
3.按行/列處理樣式: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'])
# 創建樣式方法,每列最大值填充黃色
# axis:0爲列,1爲行,默認爲0
# subset:索引
#s.max會返回一個Series