python - 使用 Pandas 对重复项进行条件格式化

标签 python pandas filter conditional-formatting pandas-styles

我有一个包含 6 列的数据框。我想对其中的两列进行条件格式设置。所以我的数据框看起来像这样

enter image description here

我想突出显示 College 和 College_F2 列中的重复值。
之后我的数据框将如下所示

enter image description here

为此编写的代码如下所示:

dataFrame_file = pd.read_excel(util.comcastFile2Path(), sheet_name='Sheet1')

def dummy_color(x):
    c1 = 'background-color:red'
    c2 = ''
    cond = dataFrame_file.stack().duplicated(keep=False).unstack()
    df1 = pd.DataFrame(np.where(cond, c1, c2), columns=x.columns, index=x.index)
    return df1

dataFrame_file.style.apply(dummy_color,axis=None,subset=['College', 'College_F2']).to_excel(util.comcastFile2Path)

这个代码给我的错误是
ValueError: Shape of passed values is (6, 6), indices imply (6, 2)

我使用的 IDE 是 PyCharm。
如何解决这个问题?

提前致谢。

最佳答案

在解决方案中必须使用所有 DataFrame,所以省略了 subset参数和在 cond过滤列以检查重复项并添加 DataFrame.reindex 用于填充False到所有其他列:

def dummy_color(x):
    c1 = 'background-color:red'
    c2 = ''
    cond = (x[['College', 'College_F2']].stack()
                                        .duplicated(keep=False)
                                        .unstack()
                                        .reindex(x.columns, axis=1, fill_value=False))
    df1 = pd.DataFrame(np.where(cond, c1, c2), columns=x.columns, index=x.index)
    return df1

dataFrame_file.style.apply(dummy_color,axis=None).to_excel(util.comcastFile2Path)

像@anky_91 提到的更简单的是将子集参数与 x 一起使用为 cond变量,我认为原因是 x变量只是由 subset 过滤的列列表:
def dummy_color(x):
    c1 = 'background-color:red'
    c2 = ''
    cond = x.stack().duplicated(keep=False).unstack()
    df1 = pd.DataFrame(np.where(cond, c1, c2), columns=x.columns, index=x.index)
    return df1

dataFrame_file.style.apply(dummy_color,axis=None, subset=['College', 'College_F2']).to_excel(util.comcastFile2Path)

关于python - 使用 Pandas 对重复项进行条件格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700768/

相关文章:

ios - 如何过滤掉第7个字符为冒号的数组对象?

python - 通过直方图匹配比较图像

python - 如何创建一个具有一个索引键列和多个值列的字典

python - PyAudio 无法在 'unable to open slave' 的 Ubuntu 14.04 上使用麦克风

python - Pandas:添加满足条件的元素的渐进计数列

python - 关于格式化 DataFrame 以与 matplotlib 一起使用的问题

arrays - Swift 根据另一个 Bool 数组过滤其他数组

javascript - 过滤javascript对象

python - P4 命令行说明,用于从模板创建工作区并对客户端规范进行其他更改

Python使用pandas每三行转列