1

I have a dataframe 'df' like this

enter image description here

How do I s set he background color of the column 'wt' based on the column 'item'.
If 'item' is 'apple', the value in the 'wt' column should have a background colour of 'orange'
If 'item' is 'orange', the value in the 'wt' column should have a background colour of 'green' ... enter image description here

1

1 Answer 1

1

I skipped the column wt (because the idea should be clear even without it) and coloured column ht. Use:

import pandas as pd
import numpy as np

df = pd.DataFrame({'item': range(7), 'ht': np.random.randint(10, 50, 7), 'item': ["apple", "orange", "apple", "blueberry", "banana", "orange", "apple"]})

color = {"apple": "blue", "orange": "green", "blueberry": "red", "banana": "purple"}



def color_fruit(s):
    return ['background-color: ' + color[s["item"]] for s_ in s]


df.style.apply(color_fruit, axis=1)

This gives you:

enter image description here

Or you can use:

def color_fruit(s):
    return ['background-color: None', 'background-color: ' + color[s["item"]]]


df.style.apply(color_fruit, subset=['item', 'ht'], axis=1)

To get:

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.