有条件地格式化 Python pandas 单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41203959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:34:23  来源:igfitidea点击:

Conditionally format Python pandas cell

pythonpandasdataframehighlightconditional-formatting

提问by thatMeow

I am trying to color, highlight, or change fond of Python pandas DataFrame based on the value of the cell. e.g. if the cells on each rows are bigger than the cell in the first column of that row, then highlight the cell as red (or any other color), otherwise leave it as it is.

我正在尝试根据单元格的值对 Python pandas DataFrame 进行颜色、突出显示或更改。例如,如果每行上的单元格大于该行第一列中的单元格,则将单元格突出显示为红色(或任何其他颜色),否则保持原样。

I wrote a for loop here:

我在这里写了一个 for 循环:

for index in range(0, df.shape[0]):
    for column in range(1, df.shape[1]): # from 1 not from 0 because I only need # to compare the 2nd to the last cell of each row with the 1st cell in the row 

        if df.iloc[index][column] - df_BDE_n_months_avg_std_pct.iloc[index][0] > 0:
            then "PLEASE PUT YOUR HELP HERE, I NEED A PIECE OF CODE THAT CAN HIGHLIGHT THE CELL"
        else:
            "DO NOTHING"

So far I haven't found a way to do it. Any help will be great.

到目前为止,我还没有找到一种方法来做到这一点。任何帮助都会很棒。

回答by Psidom

From the style docs:

样式文档:

You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame.style property.

您可以使用 DataFrame.style 属性应用条件格式,即根据其中的数据应用 DataFrame 的视觉样式。

import pandas as pd
df = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background: red" if v > x.iloc[0] else "" for v in x], axis = 1)

enter image description here

enter image description here



Edit: to format specific cells, you can add condition checkers to check the name of element with Series.iteritems()or check the index with enumerate(), e.g. if you want to format starting from column 3, you can use enumerate and check the index:

编辑:要格式化特定单元格,您可以添加条件检查器来检查元素名称Series.iteritems()或检查索引enumerate(),例如,如果您想从第 3 列开始格式化,您可以使用 enumerate 并检查索引:

df = pd.DataFrame([[2,3,-3], [3,2,7], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background-color: #ff33aa" 
                          if (i >= 2 and (v > x.iloc[0] + x.iloc[1] 
                                          or v < x.iloc[0] - x.iloc[1])) 
                          else "" for i, v in enumerate(x)], axis = 1)

enter image description here

enter image description here

回答by Zoe L

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(4,3))
df.style.applymap(lambda x: 'background-color : yellow' if x>df.iloc[0,0] else '')

df

df