2

I am trying to draw a colorful table, like this.

enter image description here

this post provides an approach.

from datetime import datetime, timedelta
import pandas as pd

name = ['Diego', 'Luis', 'Vidal', 'John', 'Yusef']
id = ['b000000005', 'b000000015', 'b000000002', 'b000000011', 'b000000013']
cel = [7878, 6464, 1100, 4545, 1717]
date = pd.to_datetime(['2017-05-31 20:53:00', '2017-05-11 20:53:00', '2017-05-08 20:53:00', 
                       '2017-06-06 20:53:00', '2017-06-06 20:53:00'])

df = pd.DataFrame({'Name':name,'ID':id,'Cel':cel,'Date':date})

def color(val):
    if val < datetime.now():
        color = 'green'
    elif val > datetime.now():
        color = 'yellow'
    elif val > (datetime.now() + timedelta(days=60)):
        color = 'red'
    return 'background-color: %s' % color

df.style.applymap(color, subset=['Date'])

exactly same code from that post, produces a different output.

enter image description here

the borders are missing, the color is also different from the one in the post.

what am i missing?

2 Answers2

2

First use pandas style for set background colors with custom function and then Styler.set_table_styles for set css styles:

df = pd.DataFrame({'Red':[1,1,0,0,0],'Yellow':[0,0,1,0,1],'Green':[0,0,0,1,0]})
print (df)

def color(x): 
   c1 = 'background-color: green'
   c2 = 'background-color: yellow'
   c3 = 'background-color: red'
   c4 = '' 
   m = x == 1
   print (m)

   df1 = pd.DataFrame(c4, index=x.index, columns=x.columns)
   df1.loc[m['Red'], 'Red'] = c1
   df1.loc[m['Yellow'], 'Yellow'] = c2
   df1.loc[m['Green'], 'Green'] = c3
   return df1

df.style.apply(color,axis=None).set_table_styles(
   [{
       'selector': 'th',
       'props': [
           ('background-color', 'blue'),
           ('color', 'white'),
           ('border-color', 'black'),
           ('border-style ', 'solid'),
           ('border-width','1px')]
   },
    {
       'selector': 'td',
       'props': [
           ('border-color', 'black'),
           ('border-style ', 'solid'),
           ('border-width','1px')]
   },
    {'selector': '.row_heading',
          'props': [('display', 'none')]},
    {'selector': '.blank.level0',
          'props': [('display', 'none')]}])

pic

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0
  1. datetime.now() is different from the linked post (May2017) and your post (May2019), hence the difference in color.

  2. You don't see the lines because your jupyter theme default's different. The code only colors the target cells. Here's the output of the same code on my computer:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74