【问题标题】:Conditional formatting on Duplicates using pandas使用熊猫对重复项进行条件格式设置
【发布时间】:2020-04-29 05:32:05
【问题描述】:

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

我想突出显示 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。 如何解决这个问题?

提前致谢。

【问题讨论】:

  • 请通过df.head().to_dict()提供(至少是您的初始)数据框
  • @rpanai dataFrame_file = pd.read_excel(util.comcastFile2Path(), sheet_name='Sheet1') 这就是我提供数据帧的方式。

标签: python pandas filter conditional-formatting pandas-styles


【解决方案1】:

在解决方案中必须使用所有 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)

【讨论】:

  • 很有趣,想知道为什么解决方案不起作用,除了 cond 行,其中 dataFrame_file 需要替换为 x 并且它适用于我,但这是一个不错的选择:)
【解决方案2】:
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-04-28
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    相关资源
    最近更新 更多