有条件地格式化 Python pandas 单元格 [英] Conditionally format Python pandas cell

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

问题描述

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

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

 for index in range(0, df.shape[0]):for column in range(1, df.shape[1]): # from 1 not from 0 因为我只需要#将每行的第二个和最后一个单元格与行中的第一个单元格进行比较如果 df.iloc[index][column] - df_BDE_n_months_avg_std_pct.iloc[index][0] >0:然后请在此处提供帮助,我需要一段可以突出显示单元格的代码"别的:没做什么"

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

解决方案

来自

<小时>

Edit:要格式化特定单元格,您可以添加条件检查器以使用 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: ["背景颜色: #ff33aa"如果 (i >= 2 并且 (v > x.iloc[0] + x.iloc[1]或 v 

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.

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.

解决方案

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.

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)


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天全站免登陆