如同Excel,在python中也可以使用条件格式(conditional formatting),使用DataFrame.style属性是格式化与展示的好方法,这个属性返回一个Styler 对象。
本文主要说说在使用相应的style函数时候如何使用切片,在官方文档中是这样描述的:
Both Styler.apply, and Styler.applymap accept a subset keyword. This
allows you to apply styles to specific rows or columns, without having
to code that logic into your style function.The value passed to subset behaves similar to slicing a DataFrame.
A scalar is treated as a column label
A list (or series or numpy array) (is treated as a column label )
A tuple is treated as (row_indexer, column_indexer)Consider using pd.IndexSlice to construct the tuple for the last one
In [12]:
df.style.apply(highlight_max, subset=['B', 'C', 'D'])
Out[12]:
A B C D E
0 1 1.32921 nan -0.31628 -0.99081
1 2 -1.07082 -1.43871 0.564417 0.295722
2 3 -1.6264 0.219565 0.678805 1.88927
3 4