简体   繁体   English

如何比较两列值并根据两列值对其中一列应用条件格式?

[英]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.

相关问题 如何比较两列的值并根据比较对值重新排序 - How to compare the values of two columns and reorder the values based on comparison 数据框:根据值应用于两列 - data frames: apply on two columns based on values Pandas Dataframe:如何比较一行的两列中的值是否等于后续行的同一列中的值? - Pandas Dataframe: how can i compare values in two columns of a row are equal to the ones in the same columns of a subsequent row? 基于2列的值的条件切片 - conditional slicing based on values of 2 columns 大熊猫:如何比较两列的浮点值 - pandas: How to compare float values of two columns 如何根据相应系列列中的值对一系列列应用函数? - How to apply a function on a series of columns, based on the values in a corresponding series of columns? Python - 比较两列功能,返回两者不相同的值 - Python - Compare two columns of features, return values which are not common to both 如何根据条件比较两列并分别打印包含(两列的)任一值的新列? - How can I compare two columns and print a new column containing either of the values (of the two columns) respectively according to a condition? 如何根据来自其他两列的值的分组总和创建新的值列? - How can I create a new column of values based on the grouped sum of values from two other columns? 使用pandas,如何比较两个数据帧中2列之间的值并将它们推送到新的数据帧? - Using pandas, how can I compare the values between 2 columns from two dataframes and push them to a new dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM