Reputation: 2223
I have a dataframe 'df' like this
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' ...
Upvotes: 1
Views: 2238
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:
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:
Upvotes: 1