0

I've created a pandas dataframe and I want to then add background-color:red to any selected column in the dataframe and display the dataframe in html with the highlighted column.

My table is shaped in the following way:

import pandas as pd
import numpy as np

np.random.seed(24)
frame = pd.DataFrame({'A': np.linspace(1, 10, 10)})
frame = pd.concat([frame, pd.DataFrame(np.random.randn(10, 12), 
columns=list('BCDEFGHIJKLM'))],axis=1)

This function I found on another stackoverflow page of a similar issue, but fails:

(attempts to look for column by position)

def highlighter(col):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=col.index, columns=col.columns)
    df1.iloc[:, 8] = r
    return df1
tab = frame.style.apply(highlighter, axis=None).render()    
print(tab) 

This is another function I created but also fails:

(attempts to look for column by calling a specific column name)

def highlighter(df, col):
    df = pd.DataFrame()
    return ['background-color:red' if col in df.columns else 'background-color:white']

tab = frame.style.apply(highlighter(col='C'), axis=None).render()
print(tab)

When I print the rendered table, the table should have a single column that has a background color of red but I see no such highlighting

cs95
  • 379,657
  • 97
  • 704
  • 746
swagless_monk
  • 441
  • 6
  • 21

1 Answers1

1

try this:

def highlighter(col):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=col.index, columns=col.columns)
    df1.iloc[:, 8] = r
    return df1
tab = frame.style.apply(highlighter, axis=None)

with open('tab.html', 'w') as html:
    html.write(tab.render())

enter image description here

Zanshin
  • 1,262
  • 1
  • 14
  • 30
  • Turns out the solution was fairly simple, the answer is [here](https://stackoverflow.com/questions/53659078/coloring-single-column-of-pandas-dataframe-to-html/53678835#53678835). There is clarification for the solution in the comments – swagless_monk Jan 06 '19 at 22:27
  • Why was this question posted then? Btw, mine is the answer to this one – Zanshin Jan 06 '19 at 22:42
  • Answer in link above took time to correct, you post answer before I could delete. – swagless_monk Jan 06 '19 at 22:59