如果某个列包含某个字符串,我会尝试更改数据框中的背景色,但我似乎无法使其正常工作。到目前为止,我有以下代码:
def highlight_cells(StartingDataFrame):
if StartingDataFrame[StartingDataFrame['HRC'].str.contains("HRC")]:
return ['background-color: red']*5
else:
return ['background-color: white']*5
StartingDataFrame.style.apply(highlight_cells, axis=1)
但它似乎对细胞没有任何作用。我做错什么了吗
代码:
StartingDataFrame = pd.DataFrame({'HRC':['aaa','HRD ','HRC oo'],
'A':[1,2,3]})
def highlight_cells(x):
c1 = 'background-color: red'
c = 'background-color: white'
#if True are strings
m1 = StartingDataFrame['HRC'].str.contains("HRC")
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1.loc[m1, 'HRC'] = c1
return df1
StartingDataFrame.style.apply(highlight_cells,axis=None)
StartingDataFrame.to_excel("outputTest.xlsx")
您可以使用自定义函数创建样式的DataFrame:
另一种解决方案是通过
in
为测试值选择列:编辑:在您的解决方案中,需要重新分配:
相关问题 更多 >
编程相关推荐