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