python-----DataFrame.style (三、切片)

本文介绍了如何在Python的DataFrame中使用style属性进行条件格式化,特别是针对多级索引的切片操作。通过Styler对象的apply和applymap方法,利用subset关键字可以对特定行或列应用样式。在多级索引场景下,使用pd.IndexSlice能正确地选择行。文章通过示例展示了如何使用pd.IndexSlice在Style属性中进行有效切片,并提醒注意在subset中元组的第二个参数无需写冒号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如同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 	
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值