gpt4 book ai didi

python - 如何在 Pandas 数据框中用不同颜色为 bool 值着色

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:49 25 4
gpt4 key购买 nike

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)

pic

如果还想删除索引值:

dataframe.style.\
applymap(color_negative_red).\
to_excel('df.xlsx', index=False)

pic1

关于python - 如何在 Pandas 数据框中用不同颜色为 bool 值着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53203980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com