[英]Color in cell containing a string Pandas
如果列包含某个字符串,我正在尝试更改 dataframe 中的背景颜色,但我似乎无法让它工作。 到目前为止,我有以下代码:
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")
您可以使用自定义 function 来创建 styles 的 DataFrame:
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", na=False)
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1.loc[m1, 'HRC'] = c1
return df1
(StartingDataFrame.style.apply(highlight_cells,axis=None)
.to_excel("outputTest.xlsx", index=False))
另一种解决方案是通过in
选择测试值的列:
def highlight_cells(val):
color = 'red' if 'HRC' in val else 'white'
return f'background-color: {color}'
(StartingDataFrame.style.applymap(highlight_cells, subset=['HRC'])
.to_excel("outputTest.xlsx", index=False))
编辑:在您的解决方案中需要分配回:
styles = StartingDataFrame.style.apply(highlight_cells,axis=None)
styles.to_excel("outputTest.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.