如何在 pandas 数据框中用不同颜色为布尔值着色
How to color boolean values by different colors in pandas dataframe
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)
试试这个(这里你可以使用 apply
):
def f(x):
df = x.copy()
for i in df.columns:
df.loc[df[i]=='TRUE',i]=='background-color: yellow'
return df
df=df.style.apply(f, axis=None)
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)
试试这个(这里你可以使用 apply
):
def f(x):
df = x.copy()
for i in df.columns:
df.loc[df[i]=='TRUE',i]=='background-color: yellow'
return df
df=df.style.apply(f, axis=None)