4

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

在此处输入图像描述

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

在此处输入图像描述

为此编写的代码如下所示:
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。如何解决这个问题?

提前致谢。

4

2 回答 2

2

在解决方案中,必须使用所有 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)
于 2020-01-12T06:24:29.350 回答
0
def dummy_color(x):
    color = 'red' if (len(dataFrame_file[dataFrame_file['College'] == x]) + len(dataFrame_file[dataFrame_file['College_F2'] == x])) > 1 else ''
    return 'background-color: %s' % color

dataFrame_file.style.applymap(dummy_color, subset=['College', 'College_F2']).to_excel(util.comcastFile2Path)
于 2020-01-12T06:20:48.307 回答