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

标签 python pandas dataframe conditional-formatting pandas-styles

我正在尝试根据单元格的值对 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 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"

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

最佳答案

来自 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)

enter image description here


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

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

关于python - 有条件地格式化 Python pandas 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203959/

相关文章:

python - sqlalchemy 是否可以添加字段级别规则,即两个特定列不能同时为 None?

python - lambda python 3 的意外输出

python - 试图让 Anaconda3 在 Mac 上运行

python - Pandas /matplotlib : faceting bar plots

python - 如何从 DataFrame 图中排除几列?

python - scikit learn 的 fit_transform 是否也会转换我的原始数据框?

r - 如何在r中随机保留一个重复行(不是第一个重复行)

python - 如何查询 pandas 数据框的正则表达式?

python - 通过多索引列切片谓词过滤 DataFrame 中的行

python - 比较 2 个 pandas 数据框列并根据值是否相同创建新列