I am using pandas styler to give some columns a background color, based on the name of the column header. While this works as intended, the background color of the column header doesn't change.
Here is the part in my script where thy style is applied:
def highlight_col(x):
if x.name in added_columns:
return ['background-color: #67c5a4']*x.shape[0]
elif x.name in dropped_columns:
return ['background-color: #ff9090']*x.shape[0]
else:
return ['background-color: None']*x.shape[0]
old = old.style.apply(highlight_col, axis=0)
Is there a way to apply the style.apply()-function not only to the cells below the column header, but the complete column including the column header?
Edit: For clarification here is a screenshot of the excel output: screenshot of excel output
"Header 2" should have the same background color as the cells below it.
答案 0 :(得分:0)
好的,我想我想出了一种使用html'selectors'处理列标题格式的方法:
将您的大部分代码用作设置:
df = pd.DataFrame('some value', columns=['Header1','Header2','Header3'], index=np.arange(12))
added_columns = 'Header2'
dropped_columns = 'Header1'
def highlight_col(x):
if x.name in added_columns:
return ['background-color: #67c5a4']*x.shape[0]
elif x.name in dropped_columns:
return ['background-color: #ff9090']*x.shape[0]
else:
return ['background-color: None']*x.shape[0]
col_loc_add = df.columns.get_loc(added_columns) + 2
col_loc_drop = df.columns.get_loc(dropped_columns) + 2
df.style.apply(highlight_col, axis=0)\
.set_table_styles(
[{'selector': f'th:nth-child({col_loc_add})',
'props': [('background-color', '#67c5a4')]},
{'selector': f'th:nth-child({col_loc_drop})',
'props': [('background-color', '#ff9090')]}])
输出:
注意:我正在使用f-string,这是Python 3.6+的一项功能。
答案 1 :(得分:0)
您可以使用np.vstack()
来堆叠列名,如下所示,并创建一个新的数据框以应用该功能,然后使用header=False
导出到excel:
使用@Scott的数据和piR的功能, 设置:
df = pd.DataFrame('some value', columns=['Header1','Header2','Header3'], index=np.arange(12))
def f(dat, c='red'):
return [f'background-color: {c}' for i in dat]
您可以这样做:
pd.DataFrame(np.vstack((df.columns,df.to_numpy())),columns=df.columns).style.apply(
f,subset=['Header2']).to_excel('file.xlsx',header=False,index=False)