目录
Pandas提供了style功能,可以直接实现excel里的高亮、色阶、数据条、单元格格式设置、字体设置等等功能,简单场景下不需要把数据导出再调整样式了,本文逐条盘点一下

- import pandas as pd
- import numpy as np
-
- np.random.seed(0)
- df = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
- df

- def color_negative_red(val):
-
- color = 'red' if val < 0 else 'black'
- return 'color: %s' % color
-
- df.style.applymap(color_negative_red,subset=['A','B','C','D'])

- (
- df
- .style
- .applymap(color_negative_red,subset=['A','B','C','D'])
- .apply(highlight_max,subset=['A','B','C','D'])
- )

df.style.format("{:.2%}",subset=['A','B'])

- df2=df.copy()
- df2.loc[0,'B']=np.nan
- df2.loc[3]=np.nan
- df2.style.format(None, na_rep="-")

- import seaborn as sns
-
- cm = sns.light_palette("green", as_cmap=True)
- s = df.style.background_gradient(cmap=cm)
- s

- (
- df
- .style
- .format("{:.2%}",subset=['A','B','C','D'])
- .bar(subset=['A', 'B'], color='#d65f5f')
- )

- col_l=['A','B','C','D']
- (
- df.style
- .format("{:.2%}",subset=['A','B','C','D'])
- .set_properties(**{'text-align': 'center'}, subset=col_l)
- .set_properties(**{'font-size': '10pt'}, subset=col_l)
- .set_properties(**{'font-weight': 'bold'}, subset=col_l)
- .set_properties(**{'color': 'black'}, subset=col_l)
- )

关注公众号 Python风控模型与数据分析,回复 Pandas表格样式 获取本篇数据及代码