Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas style function to highlight specific columns

I have been trying to write a function to use with pandas style. I want to highlight specific columns that I specify in the arguments. This is not very elegant, but for example:

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))  def highlight_cols(df, cols, colcolor = 'gray'):     for col in cols:         for dfcol in df.columns:             if col == cols:                 color = colcolor     return ['background-color: %s' % color]*df.shape[0] 

then call with:

data.style.apply(highlight_cols(cols=['B','C'])) 

I get an error: 'Series' object has no attribute 'columns'

I think I fundamentally don't quite understand how the styler calls and applyies the function.

like image 754
Maria Petrova Avatar asked Jan 14 '17 20:01

Maria Petrova


People also ask

How do I select certain columns in Python?

To select a single column, use square brackets [] with the column name of the column of interest.

How do I use conditional formatting in pandas?

One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .


2 Answers

I think you can use Slicing in Styles for select columns B and C and then Styler.applymap for elementwise styles.

import pandas as pd import numpy as np  data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC')) #print (data)  def highlight_cols(s):     color = 'grey'     return 'background-color: %s' % color  data.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']]) 

pic

If you want more colors or be more flexible, use Styler.apply(func, axis=None), the function must return a DataFrame with the same index and column labels:

import pandas as pd import numpy as np  data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC')) #print (data)  def highlight_cols(x):     #copy df to new - original data are not changed     df = x.copy()     #select all values to default value - red color     df.loc[:,:] = 'background-color: red'     #overwrite values grey color     df[['B','C']] = 'background-color: grey'     #return color df     return df      data.style.apply(highlight_cols, axis=None) 

pic1

like image 59
jezrael Avatar answered Sep 23 '22 08:09

jezrael


You can do it bit more dynamically:

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))  # dictionary of column colors coldict = {'A':'grey', 'C':'yellow'}  def highlight_cols(s, coldict):     if s.name in coldict.keys():         return ['background-color: {}'.format(coldict[s.name])] * len(s)     return [''] * len(s)  data.style.apply(highlight_cols, coldict=coldict) 

enter image description here

like image 24
MaxU - stop WAR against UA Avatar answered Sep 26 '22 08:09

MaxU - stop WAR against UA