[英]How can I compare two columns values and apply conditional formatting on one of the columns based on both columns values?
I have a data frame with scores for Q2, Q3 and Q4.我有一个包含 Q2、Q3 和 Q4 分数的数据框。 If Q4's score is greater than Q3, I'd like to color the cell green.如果 Q4 的分数大于 Q3,我想将单元格涂成绿色。 If Q4's score is less than Q3, I'd like to color the cell red.如果 Q4 的分数低于 Q3,我想将单元格涂成红色。 If Q3 and Q4 have the same score, I'd like to leave the cell white.如果 Q3 和 Q4 的分数相同,我想将单元格留白。
Here's the data and what I attempted to do这是数据和我试图做的
scores = pd.DataFrame({
'Market': ['AL', 'AR', 'AR', 'AR', 'AR'],
'Health Plan': ['HP1', 'HP1', 'HP2', 'HP3', 'HP4'],
'Network': ['Medicare', 'Ambetter', 'Medicaid', 'Medicare', 'Medicare'],
'Q2': [72,51,49,70,62],
'Q3': [72,60,59,75,55],
'Q4': [84,72,75,73,62]})
def color_cells(val):
color = 'green' if val > scores['Q3'] else 'red' if val < scores['Q3'] else 'white'
return 'background-color: %s' % color
scores.style.applymap(color_cells, subset='Q4')
print(scores)
And this is the error I am getting这是我得到的错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I would suggest to use np.select
to create a style array based on the conditions then apply
the style array on the column Q4
我建议使用np.select
根据条件创建样式数组,然后在Q4
列上apply
样式数组
colors = np.select(
[scores['Q4'] > scores['Q3'], scores['Q4'] < scores['Q3']],
['background: green', 'background: red'], 'background: white'
)
scores.style.apply(lambda s: colors, subset='Q4')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.