pandas小技巧-花哨的DataFrame

最近github上发现了一个库(plottable),可以用简单的方式就设置出花哨的 DataFrame 样式。

github上的地址:github.com/znstrider/p...

1. 安装

通过 pip 安装:

bash 复制代码
pip install plottable

2. 行的颜色

使用 plottable的API,调整背景和字体的颜色非常方便。

2.1. 奇偶行不同颜色

奇偶行设置不同的颜色,让表格看起来有层次感。

python 复制代码
import numpy as np

from plottable import Table

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])
tbl = Table(df,
            odd_row_color="#f0f0f0",
            even_row_color="#e0f6ff"
           )

2.2. 背景和字体颜色

对于复杂的显示要求,可以逐行设置背景色和字体的颜色。

python 复制代码
import numpy as np

from plottable import Table

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])
tbl = Table(df)
tbl.rows[0].set_facecolor("red")
tbl.rows[0].set_fontcolor("white")

tbl.rows[1].set_facecolor("blue")
tbl.rows[1].set_fontcolor("white")

tbl.rows[2].set_facecolor("green")
tbl.rows[2].set_fontcolor("white")

tbl.rows[3].set_facecolor("gray")
tbl.rows[3].set_fontcolor("white")

tbl.rows[4].set_facecolor("purple")
tbl.rows[4].set_fontcolor("white")

上例中每一行的背景设置了不同的颜色,字体都设置为白色。

3. 值的显示

调整颜色,字体属于基本的设置,plottable强大之处在于可用图形化的方式来显示数据,

让我们可以一眼看出数据的大小和差距。

比如,下面的示例用 ColumnDefinition 来使用 plottable内置的数据显示方式。

python 复制代码
import numpy as np

from matplotlib.colors import LinearSegmentedColormap

from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])

print(df) # 显示原始数据

cmap = LinearSegmentedColormap.from_list(
    name="bugw", colors=["#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"], N=256
)
tab = Table(
    df,
    textprops={"ha": "center"},
    column_definitions=[
        ColumnDefinition("index", textprops={"ha": "left"}),
        ColumnDefinition("A", plot_fn=percentile_bars, plot_kw={"is_pct": True}),
        ColumnDefinition(
            "B", width=1.5, plot_fn=percentile_stars, plot_kw={"is_pct": True}
        ),
        ColumnDefinition(
            "C",
            plot_fn=progress_donut,
            plot_kw={"is_pct": True, "formatter": "{:.0%}"},
        ),
        ColumnDefinition(
            "D",
            width=1.25,
            plot_fn=bar,
            plot_kw={
                "cmap": cmap,
                "plot_bg_bar": True,
                "annotate": True,
                "height": 0.5,
                "lw": 0.5,
                "formatter": decimal_to_percent,
            },
        ),
    ],
)

原始数据显示:

plottable强化之后显示:

4. 图文混合

最后,演示一个通过 plottable 在表格中插入图片的示例。

其中数据来源是 2023 王者荣耀春季赛各个战队的数据

主要为了演示表格中插入图片(图片是各个战队的logo),所以只挑选了4个列来展示。

python 复制代码
import pandas as pd
import numpy as np

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut
from plottable.plots import circled_image

matplotlib.rcParams["font.sans-serif"] = ["Microsoft YaHei Mono"]
matplotlib.rcParams["axes.unicode_minus"] = False

df = pd.read_csv("d:/share/data.csv")
df = df.set_index("排名")
df["胜率"] = df["胜场"] / df["比赛场次"]
df["logo"] = "d:/share/wzry-logos/" + df["战队"] + ".png"
df = df.drop(columns=["胜场", "比赛场次", "场均KDA"])

fig, ax = plt.subplots(figsize=(12, 12))

col_defs = [
        ColumnDefinition("排名", textprops={"ha": "left"}),
        ColumnDefinition(
            name="logo",
            title="",
            textprops={"ha": "center"},
            width=0.5,
            plot_fn=circled_image,
        ),
        ColumnDefinition("战队", textprops={"ha": "center"}),
        ColumnDefinition(
            "胜率",
            plot_fn=progress_donut,
            plot_kw={"is_pct": True, "formatter": "{:.0%}"},
        ),
    ]

tbl = Table(
    df,
    ax=ax,
    textprops={"ha": "center", "fontsize": 20},
    column_definitions=col_defs,
)

上面示例中用到的数据和logo图标分享在:
url11.ctfile.com/f/45455611-... (访问密码: 6872)

有兴趣可以试试看上面的示例,或者继续深入探索 plottable 的强大显示功能。

相关推荐
weixin_307779135 小时前
PySpark实现导出两个包含多个Parquet数据文件的S3目录里的对应值的差异值分析
python·数据分析·spark·云计算
几米哥7 小时前
Data Science Agent in Colab完全指南:AI驱动的智能数据分析助手
数据分析·gemini
m0_7482365811 小时前
Python数据分析案例30——中国高票房电影分析(爬虫获取数据及分析可视化全流程)
爬虫·python·数据分析
weixin_3077791315 小时前
Python Pandas实现dataframe导出为Excel 2007格式的文件并设置合适的列宽度
开发语言·python·excel·pandas
ALPH_21 小时前
R语言的基础命令及实例操作
开发语言·数据分析·r语言·perl·r语言-4.2.1
刘大猫261 天前
一、MyBatis简介:MyBatis历史、MyBatis特性、和其它持久化层技术对比、Mybatis下载依赖包流程
人工智能·数据挖掘·数据分析
秀儿还能再秀1 天前
淘宝母婴购物数据可视化分析(基于脱敏公开数据集)
python·数据分析·学习笔记·数据可视化
计算机老学长1 天前
基于Python的商品销量的数据分析及推荐系统
开发语言·python·数据分析
伪编辑科学家2 天前
[数据可视化的python脚本实现]关于餐厅消费的不同维度分析
python·信息可视化·pandas·matplotlib
生信大杂烩2 天前
Xenium数据分析 | 数据预处理、单细胞降维聚类、细胞类型定义
数据挖掘·数据分析·聚类