gpt4 book ai didi

python - 如何使用 style.applymap() 为数据框中的行着色?

转载 作者:行者123 更新时间:2023-12-04 15:20:43 24 4
gpt4 key购买 nike

<分区>

我想为 DataFrame 对象 df 中的“Grand Total”行和“Total”列着色,对此我尝试了以下操作:

import pandas as pd

# Function to set background highlight colour.
def bg_colour (val):
colour = '#ffff00'
return 'background-color: %s' % colour

df = pd.DataFrame({'Category': ['A','B','C','D','Grand Total'], 'Total': [1,2,3,4,10]})
t1 = df.style.applymap(bg_colour, subset = ['Total'])
dfT = df.T
dfT = dfT.style.applymap(bg_colour, subset = [4])
t1T = t1.T

但是,当编译器到达代码的最后一行时,会出现以下错误:

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-48-c0c380b9c518> in <module>
12 dfT = dfT.style.applymap(bg_colour, subset = [4])
13 display(dfT)
---> 14 t1T = t1.T

AttributeError: 'Styler' object has no attribute 'T'

据我了解,style.applymap() 将 DataFrame 隐式转换为 Styler 类型的对象,不能将其作为 DataFrame 进一步操作。

问题 1:如何对 DataFrame 对象的行和列进行着色?

问题2:如何将Styler类型的对象转换为DataFrame类型的对象?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com