Suraj_j
Suraj_j

Reputation: 184

Using Dataframes style.apply for Highlighting based on comparative values

In my code I am using df.style.applymap() to render HTML onto my intranet Webpage. I have the following Code which is working Well for me, (2 Columns are passed on to my function highlight_vals).

def highlight_vals(val, color='green', color1='red'):
        if val > 0.8:
            return 'background-color: %s' % color
        elif val < -0.9:
            return 'background-color: %s' % color1
        else:
            return ''

Now, I want to make a similar function (or ever use the current highlight_vals) in order to achieve Comparative Highlighting with the condition on the lines of:
if ValinColumn1 > 0.25 * ValinColumn2: # (For same Row/Record)
return 'background-color: %s' % color #Yellow/Highlights.


I am using the above function in my views.py:
httresp += df.style.applymap(highlight_vals,subset=[col1,col2])

Upvotes: 2

Views: 5299

Answers (2)

hellpanderr
hellpanderr

Reputation: 5896

You need to use apply(axis=1) to iterate through rows:

def highlight_vals(row, cols=['A', 'B'], color='green'):
    a, b = cols
    styles = {col: '' for col in row.index}
    if row[a] > 0.25 * row[b]:
        styles[a] = 'background-color: %s' % color
        styles[b] = 'background-color: %s' % color
    return styles

df.style.apply(lambda x: highlight_vals(x, cols=['B', 'E']), axis=1)

enter image description here

Upvotes: 5

kevh
kevh

Reputation: 323

From this question: Difference between map, applymap and apply methods in Pandas I think what you need is the function apply. It can work on multiple columns. You are using applymap which is oriented for the whole dataframe (but you go around that by selecting a column from your dataframe with df.style)

Here is a toy example:

>>> df = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B'])
>>> df['sum_A_B']=df.apply(lambda x: x['A'] + x['B'], axis=1)
>>> df
   A  B  sum_A_B
0  1  2        3
1  3  4        7

Upvotes: 0

Related Questions