Pandas Style 为数据表格美颜

您所在的位置:网站首页 表格css样式 Pandas Style 为数据表格美颜

Pandas Style 为数据表格美颜

2023-09-12 19:40| 来源: 网络整理| 查看: 265

作者:牵引小哥

来源:牵引小哥讲Python

1. 创建样式

传递样式函数的方法:

Styler.applymap: 逐个元素,返回带有CSS属性-值对的单个字符串。

Styler.apply: 列/行/表方式,返回形状相同的Series或DataFrame,其中每个值都是带有CSS属性值对的字符串。

Styler.applymap 作用于DataFrame中的每一个元素。Styler.apply 通过axis参数,每一次将一列或一行或整个表传递到DataFrame中。对于按列使用 axis=0, 按行使用 axis=1, 整个表使用 axis=None.

import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],                axis=1) df.iloc[3, 3] = np.nan df.iloc[0, 2] = np.nan # 默认无样式 df.style

「注意」: DataFrame.style 返回Styler对象的属性。

# 通过调用.render方法来查看它们 df.style.highlight_null().render().split('\n')[:10] ['',  '    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow0_col2 {',  '            background-color:  red;',  '        }    #T_98ef3b58_b54d_11ea_87c2_8056f2b2fdccrow3_col3 {',  '            background-color:  red;',  '        }                    A        B        C        D        E    ',  '                ',  '                        0',  '                        1.000000',  '                        1.329212'] 编写一个简单的样式函数,该函数会将负数涂成红色,将正数涂成黑色。 def color_negative_red(val):     """     Takes a scalar and returns a string with     the css property `'color: red'` for negative     strings, black otherwise.     """     color = 'red' if val 


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3