0

I have some data like this:


     critical_values       adf  pvalue  alpha                    decision
1%         -3.465620  3.145186     1.0   0.01  accept H0 (non-stationary)
5%         -2.877040  3.145186     1.0   0.05  accept H0 (non-stationary)
10%        -2.575032  3.145186     1.0   0.10  accept H0 (non-stationary)

I want to style the column decision 'darkorange' if df.pvalue < df.alpha and 'lightgreen' otherwise.

I like to highlight only the column DECISION.

How to do that?

I have tried this so far:

import pandas as pd

df1 = pd.read_clipboard(sep=r'\s\s+')

df1.style.apply(lambda x: ['background: lightgreen' if (x.pvalue < x.alpha)
                              else 'background: darkorange' for i in x],
               axis=1)
# This highlights all rows

This fails:

df1.style.apply(lambda x: ['background: lightgreen' if (x.pvalue < x.alpha)
                              else 'background: darkorange' for i in x],
               axis=1,
               subset=['decision'])

How to highlight only the decision column?

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169

1 Answers1

1

Try the following code:

def highlight(row):
    bgr = 'background: ' + ('lightgreen'
        if (row.pvalue < row.alpha) else 'darkorange')
    return [''] * 4 + [bgr]
df1.style.apply(highlight, axis=1)

The function should return separate style for each column. So if decision is preceded by 4 other columns then the return value should contain:

  • 4 empty strings,
  • then the style string for decision.

Of course, to see the difference in background, set alpha > pvalue in at east 1 row.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41