【Python基础】pandas的骚操作:一行 pandas 代码搞定 Excel “条件格式”!
本篇是pandas100个骚操作系列的第 7 篇:一行 pandas 代码搞定 Excel “条件格式”!
style
方法,二是要得益于pandas的链式法则
。import pandas as pd
df = pd.read_csv("test.csv")
df
![](https://filescdn.proginn.com/15c4b9402672bfae61384599ffefce73/8ac97a3d4996df0834e48bacb949514a.webp)
bar
代码如下。df.style.bar("Fare",vmin=0)
![](https://filescdn.proginn.com/8cf7db596f4e20742dcc0da35a8604bc/5d32fac5c984066a9a53ad85f8bf4043.webp)
background_gradient
,深颜色代表数值大,浅颜色代表数值小,代码如下。df.style.background_gradient("Greens",subset="Age")
![](https://filescdn.proginn.com/9077c9c670b8179515be6f02a1053fd1/eb206d79c67e5758d55226918a8db8eb.webp)
highlight_null
,表格所有缺失值都会变成高亮。df.style.highlight_null()
![](https://filescdn.proginn.com/877f380e9115c3829a9fe5ff845ca5f5/f67acc83e52c4481ff1b2f78b673b21c.webp)
pandas
的style
条件格式,用法非常简单。下面我们用链式法则将以上三个操作串起来,只需将每个方法加到前一个后面即可,代码如下。df.style.bar("Fare",vmin=0).background_gradient("Greens",subset="Age").highlight_null()
![](https://filescdn.proginn.com/d74f8daedd0cc89190efc38cd9a47a82/0edd888c40b4223b6d68266182fb79c3.webp)
style
中常用的操作,还有很多其他操作比如高亮最大值、给所有负值标红等等,通过参数subset还可以指定某一列或者某几列的小范围内进行条件格式操作。# 负值标为红色
applymap(color_negative_red)
# 高亮最大值
apply(highlight_max)
# 使某一列编程±前缀,小数点保留两位有效数字
format({"Coulumn": lambda x: "±{:.2f}".format(abs(x))})
# 使用subset进行dataframe切片,选择指定的列
applymap(color_negative_red,
subset=pd.IndexSlice[2:5, ['B', 'D']])
seaborn
的各种风格。import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
df.style.background_gradient(cmap=cm)
![](https://filescdn.proginn.com/009369b35316d78b6542efc711e0673c/1db0bec45e355c25d53dd647a53af069.webp)
Ipython
的HTML
还可以实现炫酷的动态效果。from IPython.display import HTML
def hover(hover_color="#ffff99"):
return dict(selector="tr:hover",
props=[("background-color", "%s" % hover_color)])
styles = [
hover(),
dict(selector="th", props=[("font-size", "150%"),
("text-align", "center")]),
dict(selector="caption", props=[("caption-side", "bottom")])
]
html = (df.style.set_table_styles(styles)
.set_caption("Hover to highlight."))
html
![](https://filescdn.proginn.com/ebede28fb2fd4bd3256a755e701db16e/9be95592d07fdcc2b9c39d21015a9e43.webp)
style
条件格式的所有用法,可以参考pandas的官方文档。往期精彩回顾
本站知识星球“黄博的机器学习圈子”(92416895)
本站qq群704220115。
加入微信群请扫码:
评论