python - 如何在熊猫数据框中用不同颜色为布尔值着色
问题描述
Customer_id Name Age Balance
Q1 True True True
W2 True True True
E3 True False True
T5 True True False
Y6 True True True
U7 True True True
I8 False False False
O9 True False False
P0 False False False
我想'TRUE'
在上面的数据框中用黄色突出显示或着色一个单词
这是我尝试过的代码:
def color_negative_red(val):
color = 'yellow' if val == 'TRUE' else 'black'
return 'color: %s' % color
df = dataframe.style.\
apply(color_negative_red).\
to_excel('df.xlsx')
我收到以下错误
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Customer_id')
我在这里做错了什么?
解决方案
改用:Styler.applymap
_apply
dataframe.style.\
applymap(color_negative_red).\
to_excel('df.xlsx')
您还可以通过True
if boolean 和'True'
if string 进行比较:
def color_negative_red(val):
color = 'yellow' if val == True else 'black'
return 'color: %s' % color
#python 3.6+ with f-strings
def color_negative_red(val):
color = 'yellow' if val == True else 'black'
return f'color: {color}'
#python bellow 3.6
def color_negative_red(val):
color = 'yellow' if val == True else 'black'
return 'color: {}'.format(color)
如果还想删除索引值:
dataframe.style.\
applymap(color_negative_red).\
to_excel('df.xlsx', index=False)
推荐阅读
- ruby - 如何在 Ruby 中表达这种数据类型?
- json - 有条件地确定字段的必要性
- angular - Apollo Angular Add--无法读取 tsconfig.base.json
- github - GitHub PR UI 中的选项卡大小不一致
- phpmyadmin - 无法打开 XAMPP PHP Admin,出现致命错误:未捕获错误:找不到类“PhpMyAdmin\Template”
- swift - 使滑块值只能以一种方式调整
- unity3d - unity LookAt 而不是 Forward
- javascript - 使用偏移识别图像的特定区域
- django - 生产中的子解释器错误不支持 fork
- prolog - 序言:错误的评价?