【python数据分析(26)】DataFrame表格样式设定(针对于jupyter notebook)

0. 样式创建:

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

前期准备,导入相关的库和加载数据(编程环境jupyter notebook)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d'])
sty = df.style
print(sty)
print(type(sty))

–> 输出的结果为:

<pandas.formats.style.Styler object at 0x0000000009789CF8> 
<class 'pandas.formats.style.Styler'>
1. 按元素处理样式

style.applymap(),括号内可以加入自定义的函数

def color_neg_red(val):
    if val < 0:
        color = 'red'
    else:
        color = 'black'
    return(f'color:{color}')
df.style.applymap(color_neg_red)

–> 输出的结果为:(负数显示红色,正数显示黑色)
在这里插入图片描述

2. 按行/列处理样式

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'])

–> 输出的结果为:(每列最大值填充黄色,行列的操作的话就要是列表数据)
在这里插入图片描述

3. 索引/切片样式修改
df.style.apply(highlight_max, axis = 1, 
               subset = pd.IndexSlice[2:5,['b', 'd']])

#也可先索引行再做样式:
#df[2:5].style.apply(highlight_max, subset = ['b', 'd'])

–> 输出的结果为:(核心的要点就是如何筛选DataFrame表格中的指定的区域表格:pd.IndexSlice[2:5,['b', 'd']]
在这里插入图片描述

★★★★★ 4. 表格格式处理

df.style.format() 类似之前的字符串的格式化输出显示

1) 百分数显示

df = pd.DataFrame(np.random.randn(10,4),columns=['a','b','c','d'])
df.head().style.format("{:.2%}")

–> 输出的结果为:
在这里插入图片描述
2) 小数点数显示

df.head().style.format("{:.4f}")

–> 输出的结果为:
在这里插入图片描述
3) 正负数显示

df.head().style.format("{:+.2f}")

–> 输出的结果为:
在这里插入图片描述
4) 分列进行格式显示

df.head().style.format({'b':"{:.2%}", 'c':"{:+.3f}", 'd':"{:.3f}"})

–> 输出的结果为:
在这里插入图片描述

5. 表格样式调用

Styler内置样式调用

1) 定位空值

df = pd.DataFrame(np.random.rand(5,4),columns = list('ABCD'))
df['A'][2] = np.nan
df.style.highlight_null(null_color='red')

–> 输出的结果为:
在这里插入图片描述
2) 色彩映射(渐变)

df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD'))
df.style.background_gradient(cmap='Greens',axis =1,low=0,high=1)

–> 输出的结果为:(注意axis轴参数的使用)
在这里插入图片描述
3) 条形图

df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD'))
df.style.bar(subset=['A', 'B'], color='#d65f5f', width=100)

–> 输出的结果为:(width:最长长度在格子的占比)
在这里插入图片描述
4) 分段式构建样式

df = pd.DataFrame(np.random.rand(10,4),columns = list('ABCD'))
df['A'][[2,3]] = np.nan
df.style.\
    bar(subset=['A', 'B'], color='#d65f5f', width=100).\
    highlight_null(null_color='yellow')

–> 输出的结果为:(样式之间可以相互补充)
在这里插入图片描述

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lys_828

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值