how do you style data frame in Pandas

63 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 need to apply style to this data frame based on Percent_Utilized column. I have this solution so far:

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

def color_for_avg_row(row):
    styles = [''] * len(row)
    if row['Server'] == 'Avg':
        if row['Percent_Utilized'] > 80:
            color = 'background-color: red'
        elif row['Percent_Utilized'] > 50:
            color = 'background-color: yellow'
        else:
            color = 'background-color: green'
        styles = [color for _ in row.index]
    return pd.Series(styles, index=row.index)

df_new = (df.style
              .apply(color_for_avg_row, axis=1)
              .applymap(color, subset=["Percent_Utilized"]))

df_new 

pd.isnull(val): line seem to skip over the values in color function. but now I get a different error:

  AttributeError: 'NoneType oject has no attribute 'rstrip'. 

I think when I try to style to to df_new, it is putting this error.

1

There are 1 best solutions below

0
user1471980 On BEST ANSWER

this worked:

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

def color_for_avg_row(row):
    styles = [''] * len(row)
    if row['Server'] == 'Avg':
        if row['Percent_Utilized'] > 80:
            color = 'background-color: red'
        elif row['Percent_Utilized'] > 50:
            color = 'background-color: yellow'
        else:
            color = 'background-color: green'
        styles = [color for _ in row.index]
    return pd.Series(styles, index=row.index)

df_new = (df.style
              .apply(color_for_avg_row, axis=1)
              .applymap(color, subset=["Percent_Utilized"]))