1

I have a pandas data frame that I am then writing into an Excel sheet:

Measure value lower limit upper limit
A 1 0.1 1.2
B 2 0.5 1.5
C 10 1 100

I would like to color code the column "value" based on the condition that "value" is contained between "lower limit" and "upper limit".

What I have done so far is to create an extra column called "within limits" to check that the condition is true or false, but for this case I can only find solutions in pandas that are color coding the column "within limits" itself, and not the "value" column.

Is there a way to color code based on another column value?

1 Answer 1

2

You can use a custom function:

def color(df):
    out = pd.DataFrame(None, index=df.index, columns=df.columns)
    out['value'] = (df['value']
                    .between(df['lower limit'], df['upper limit']) 
                    .map({True: 'background-color: yellow'})
                    )
    return out

df.style.apply(color, axis=None)

With parameters:

def color(df, value, low, high, color='red'):
    out = pd.DataFrame(None, index=df.index, columns=df.columns)
    out[value] = (df[value]
                    .between(df[low], df[high]) 
                    .map({True: f'background-color: {color}'})
                    )
    return out

df.style.apply(color, value='value', low='lower limit', high='upper limit',
               color='yellow', axis=None)

output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.