imdevskp
imdevskp

Reputation: 2223

How to set pandas dataframe background color based on another column

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

Upvotes: 1

Views: 2238

Answers (1)

Albo
Albo

Reputation: 1644

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

Upvotes: 1

Related Questions