最近想自己做个小程序在Ipython notebook上运行查询数据,但是输出来的表格实在是太丑了。。。

于是想着能不能美化一下格式,网上查了下,果然有很多!所以就来整理一下,便于以后查找。
1. 基本样式显示
首先来看下网上的一个例子:
from pandas import Series,DataFrame
import pandas as pd
df = {'水果':['苹果','梨','草莓'],
'数量':[3,2,5],
'价格':[10,9.4345,18]}
df = DataFrame(df)
print(df)
运行之后是这样的:

来改下输出为表格的形式,非常简单,看代码:
df.style
看图:

看起来比第一个图好看多了!接下来就是按照需求来改表格的格式啦!
2. 调整表格内文字格式
表格的文字格式可以进行调整,包括颜色,字体,小数点位数等等。使用的是df.style.format()
,其中要对制定列进行格式设置可以使用subset
参数
首先可以设置下小数点位数:
# 设置小数点后两位
df.style.format('{:.2f}',subset=['价格'])

可以指定某一列来设置,其他的格式也是类似的,都可以通过subset来指定需要改格式的列。
还可以在format的{}里面添加其他的后缀,比如说%等。
# 百分数计算
df.style.format('{:.2%}',subset=['价格'])

- 自定义函数设置颜色
表格的颜色和背景等等可以通过自定义函数进行设置。主要使用的是applymap()
# 根据不同的区间设置不同的颜色
def color_range(val):
'''
指定温度的不同区间的颜色
'''
if val > 10:
color = 'red'
elif val > 9.5:
color = 'coral'
elif val > 0:
color = 'orange'
else:
color = "skyblue"
return 'background-color: %s' % color
(df.style.format('{:.2f}',subset = ['价格'])
.applymap(color_range,subset=['价格']))

# 设置字体颜色
def color_big_red(val):
'''
当大于10时显示为红色
'''
color = 'red' if val > 10 else 'black'
return 'color: %s' % color
# df.style
(df.style.format('{:.2f}',subset = ['价格'])
.applymap(color_big_red,subset=['价格']))

还有一些其他的功能,这里有一些链接供大家参考:
1、https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
2、https://zhuanlan.zhihu.com/p/126223075
网友评论