python - 如何根据另一列设置熊猫数据框背景颜色
问题描述
我有一个像这样的数据框'df'
如何根据列“item”设置列“wt”的背景颜色。
如果 'item' 是 'apple',则 'wt' 列中的值应具有背景色 'orange'
如果 'item' 是 'orange',则 'wt' 列中的值应具有背景色 '绿色' ...
解决方案
我跳过了专栏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)
要得到:
推荐阅读
- php - Laravel - Nexmo 没有在 .ENV 文件中获取凭据
- javascript - 将文本转换为小数字javascript
- angular - RxJS - 条件 Concat 并合并响应中的对象
- javascript - 任意嵌套对象中的递归计数
- java - Java中从头开始的广度优先搜索
- blockchain - 我们如何知道区块链中每个账户的金额?
- reactjs - ECONNREFUSED - 代理来自 React 的 API 请求
- visual-studio-code - VSCode 任务,npm 脚本的用户输入
- ijson - ijson.common.IncompleteJSONError:词法错误:json 文本中的无效字符
- python - 带有 Flask 的 SQLALchemy 中的静态模型实例(夹具)