我有一个包含 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。
如何解决这个问题?
提前致谢。
最佳答案
在解决方案中必须使用所有 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/