有条件地格式化Python pandas 细胞 [英] Conditionally format Python pandas cell

查看:158
本文介绍了有条件地格式化Python pandas 细胞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I wrote a for loop here:

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.

推荐答案

来自样式文档:

您可以应用条件格式,即 DataFrame取决于其中的数据,方法是使用DataFrame.style 属性.

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

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)

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

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:

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)

这篇关于有条件地格式化Python pandas 细胞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆