如何根据另一列设置 pandas 数据框背景色
How to set pandas dataframe background color based on another column
我有一个这样的数据框'df'
如何根据列 'item'.
设置列 'wt' 的背景颜色
如果 'item' 为 'apple','wt' 列中的值的背景色应为 'orange'
如果 'item' 为 'orange',则 'wt' 列中的值的背景颜色应为 'green' ...
我跳过了专栏wt
(因为即使没有它,想法也应该很清楚)和彩色专栏ht
。使用:
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)
这给你:
或者您可以使用:
def color_fruit(s):
return ['background-color: None', 'background-color: ' + color[s["item"]]]
df.style.apply(color_fruit, subset=['item', 'ht'], axis=1)
获得:
我有一个这样的数据框'df'
如何根据列 'item'.
设置列 'wt' 的背景颜色
如果 'item' 为 'apple','wt' 列中的值的背景色应为 'orange'
如果 'item' 为 'orange',则 'wt' 列中的值的背景颜色应为 'green' ...
我跳过了专栏wt
(因为即使没有它,想法也应该很清楚)和彩色专栏ht
。使用:
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)
这给你:
或者您可以使用:
def color_fruit(s):
return ['background-color: None', 'background-color: ' + color[s["item"]]]
df.style.apply(color_fruit, subset=['item', 'ht'], axis=1)
获得: