如何将低于1的单元格中的颜色设置为绿色,将单元格中的单元格设置为0到0.5之间的黄色。
当前输出:
A B C
0 TT WW -5
1 AA WW 0
2 DD WW 5
所需:
以下代码只是写入Excel而没有颜色变化。
import pandas as pd
import numpy as np
df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
if min < val < max:
return 'background-color: %s' % color
else:
return ''
df.style.applymap(highlight_vals, subset=['C'])
def highlight_vals(val, min=0, max=0.5, color='yellow'):
if min < val < max:
return 'background-color: %s' % color
else:
return ''
df.style.applymap(highlight_vals, subset=['C'])
writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
df.to_excel(writer, startrow=0, startcol=0, index = False)
writer.save()
答案 0 :(得分:1)
这应该有效:
import pandas as pd
import numpy as np
df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
if min <= val <= max:
return 'background-color: %s' % color
else:
return ''
style_1 = df.style.applymap(highlight_vals, subset=['C'])
def highlight_vals(val, min=0, max=0.5, color='yellow'):
if min <= val <= max:
return 'background-color: %s' % color
else:
return ''
style_2 = df.style.applymap(highlight_vals, subset=['C'])
style_1.use(style_2.export())
writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
style_1.to_excel(writer, startrow=0, startcol=0, index = False)
writer.save()
我保留了两个Styler
个对象,一个又一个地应用,并将生成的对象保存到Excel而不是数据帧。还要注意我修好了你的条件。否则,由于min < val