12

I have a dataframe and would like to use the .style to highlight the first column.

I wasn't sure if there is a loop I have to use or a function

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Penny Pang
  • 535
  • 2
  • 8
  • 23

2 Answers2

18

You can solve it in one line like this:

df.style.set_properties(**{'background-color': 'red'}, subset=['A'])

where subset is the list of column names on which you want to apply the desired properties.

The result is the same as shown by @jezrael You can check other properties and possibilities for styling in pandas' website

lrvlr
  • 181
  • 1
  • 3
  • With your one line of code, can you apply to several columns with different colors for each column? – sqllearner Oct 19 '20 at 01:47
  • @sqllearner you can apply the same color to several columns just by adding them to the subset, like df.style.set_properties(**{'background-color': 'red'}, subset=['A', 'C']). But I'm not sure you can apply different colors on one line. set_properties according to the docs is : "for setting one or more non-data dependent properties". – lrvlr Oct 20 '20 at 01:42
  • @sqllearner you could solve it in two lines: \ `col_ref = {'A': 'background-color: red', 'C':'background-color:yellow'} \ df.style.apply(lambda x: pd.DataFrame(col_ref, index=df.index, columns=df.columns).fillna(''), axis=None)` – lrvlr Oct 20 '20 at 18:08
6

I think you need custom function which return DataFrame with color for first column:

np.random.seed(100)
df =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def highlight_col(x):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[:, 0] = r
    return df1    
df.style.apply(highlight_col, axis=None)

sample

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252