I understand to access the top left cell of a dataframe we need to use df.columns.name and I can see the pandas document on styling provides example to style row/column headers with apply_index (https://pandas.pydata.org/docs/user_guide/style.html)
The question I have is how to style this top left cell, say color it blue. Thanks.
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.columns.name = 'Test'
df
Update: ouroboros1's answer below is very informative and helpful. But seems like when converting the Styler object to Excel, i.e. to_excel(), the format to the top left cell is not preserved.
In the documentation (and in Export to Excel section), it is stated that "Table level styles, and data cell CSS-classes are not included in the export to Excel: individual cells must have their properties mapped by the Styler.apply and/or Styler.applymap methods".
Update: Thanks to @ouroboros1 Here is a possible solution for anyone who is interested.
d = {'col1': [1, 2], 'col2': [3, 4]}
color_matrix_df = pd.DataFrame([['background-color:yellow', 'background-color:yellow'],
['background-color:yellow', 'background-color:blue']])
df = pd.DataFrame(data=d)
df.columns.name = 'Test'
df
def colors(df, color_matrix_df):
style_df = pd.DataFrame(color_matrix_df.values, index=df.index, columns=df.columns)
return style_df.applymap(lambda elem: elem)
df_upper_left_cell = df.style.set_table_styles(
[{'selector': '.index_name',
'props': [('background-color', 'IndianRed'),
('color', 'white')]
}]
)
df_upper_left_cell.apply(colors, axis=None, color_matrix_df=color_matrix_df)
w = pd.ExcelWriter('Test.xlsx', engine='xlsxwriter')
df_upper_left_cell.to_excel(w, index=True)
wb = w.book
ws = w.sheets['Sheet1']
fmt_header = wb.add_format({'fg_color': '#cd5c5c', 'align': 'center'})
ws.write(0,0, df_upper_left_cell.data.columns.name, fmt_header)
w.save()
The above code will color the dataframe as shown below and saved the same to the Excel file.








