how do you modify styled data frame in Pandas

66 Views Asked by At

I have this data frame:

df

Server        Env.    Model   Percent_Utilized
server123     Prod     Cisco.       50
server567.    Prod     Cisco.       80
serverabc.    Prod     IBM.         100
serverdwc.    Prod     IBM.         45
servercc.     Prod      Hitachi.    25
Avg                                60

server123Uat  Uat     Cisco.       40
server567u    Uat     Cisco.       30
serverabcu    Uat     IBM.         80
serverdwcu    Uat     IBM.         45
serverccu     Uat     Hitachi      15
Avg                               42

I have style applied to this df as follows:

def color(val):
    if val > 80:
        color = 'red'
    elif val > 50 and val <= 80:
        color = 'yellow'
    else:
        color = 'green'
    return 'background-color: %s' % color

df_new = df.style.applymap(color, subset=["Percent_Utilized"])

I need to add % at the end of the numbers on Percent_Utilized columns:

resulting data frame need to look something like this:

df_new

    Server        Env.    Model   Percent_Utilized
    server123     Prod     Cisco.       50%
    server567.    Prod     Cisco.       80%
    serverabc.    Prod     IBM.         100%
    serverdwc.    Prod     IBM.         45%
    servercc.     Prod      Hitachi.    25%
    Avg                                60%
    
    server123Uat  Uat     Cisco.       40%
    server567u    Uat     Cisco.       30%
    serverabcu    Uat     IBM.         80%
    serverdwcu    Uat     IBM.         45%
    serverccu     Uat     Hitachi      15%
    Avg                               42%

when I do this:

df_new['Percent_Utilized'] = df_new['Percent_Utilized'].astype(str) + '%'

I get this error:

TypeError: 'Styler" object is not suscriptable.

1

There are 1 best solutions below

3
Quang Hoang On BEST ANSWER

df.style returns a pd.Styler object, not a pd.DataFrame object. So you cannot use .astype. You can use Styler.format like this:

df_new = df.style.applymap(color, subset=["Percent_Utilized"])\
           .format('{:.0f}%', subset=['Percent_Utilized'], na_rep='nan')
         

You'd get something like this, ignore the Avg rows as they are not read properly by read_clipboard:

enter image description here