matplotlib魔幻的表格操作

matplotlib表格操作

表格视觉样式:Dataframe.style → 返回pandas.Styler对象的属性,具有格式化和显示Dataframe的有用方法

样式创建:
① Styler.applymap:elementwise → 按元素方式处理Dataframe
② Styler.apply:column- / row- / table-wise → 按行/列处理Dataframe

1.表格样式创建
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
# 显示样式

在这里插入图片描述

# 按元素处理样式: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() → 自动调用其中的函数

在这里插入图片描述

# 按行/列处理样式: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:索引

在这里插入图片描述

# 按行/列处理样式: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:索引

在这里插入图片描述

2.表格显示控制
# 按照百分数显示

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("{:.4f}")
# 分列显示

df.head().style.format({'b':"{:.2%}", 'c':"{:+.3f}", 'd':"{:.3f}"})
3.表格样式调用
# 定位空值

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(subset=['A','B'],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','C'], 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')

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值