首页 > 解决方案 > 如何根据另一列设置熊猫数据框背景颜色

问题描述

我有一个像这样的数据框'df'

在此处输入图像描述

如何根据列“item”设置列“wt”的背景颜色。
如果 'item' 是 'apple',则 'wt' 列中的值应具有背景色 'orange'
如果 'item' 是 'orange',则 'wt' 列中的值应具有背景色 '绿色' ... 在此处输入图像描述

标签: pythonpandasdata-sciencedata-analysispandas-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)

要得到:

在此处输入图像描述


推荐阅读