3

So I figured out how to color singular cells and coloumns using the Style module in pandas. How ever, I want to color entire rows based on values in a singler cell in that row.

For instance, if a cell C in coloumn A has the value 23, color C's row in yellow.

How do I that?

1 Answer 1

7

Use:

df =  pd.DataFrame({'A':[23,25,10], 'B':[7,8,3], 'C':[8,3,1]})
print (df)
    A  B  C
0  23  7  8
1  25  8  3
2  10  3  1

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set by condition
    mask = df['A'] == 23
    df.loc[mask, :] = 'background-color: yellow'
    df.loc[~mask,:] = 'background-color: ""'
    return df    

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

picture

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

3 Comments

Cool, can you explain what exactly happens here: df.loc[mask, :] = 'background-color: red' df.loc[~mask,:] = 'background-color: ""'
It set values to DataFrame by conditions. : means set all columns if mask is True. so for second set need ~ for inverse mask.
Thank you, ~ was new to me.

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.