【发布时间】:2021-07-03 06:14:00
【问题描述】:
我有一个像这样的数据框'df'
如何根据“item”列设置“wt”列的背景颜色。
如果'item'是'apple','wt'列中的值应该有'orange'的背景色
如果'item'是'orange','wt'列中的值应该有'green'的背景色...
【问题讨论】:
标签: python pandas data-science data-analysis pandas-styles
我有一个像这样的数据框'df'
如何根据“item”列设置“wt”列的背景颜色。
如果'item'是'apple','wt'列中的值应该有'orange'的背景色
如果'item'是'orange','wt'列中的值应该有'green'的背景色...
【问题讨论】:
标签: python pandas data-science data-analysis pandas-styles
我跳过了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)
获取:
【讨论】: