Search code examples
pythonpandasexcel

Change the color of some headers in a dataframe and export to excel


I have two lists of headers and a dataframe like this:

import pandas as pd
list1 = ["A","B","C"]
list2 = ["E","F","G"]
df = pd.DataFrame(columns=list1 + list2)
# Change columns color logic
df.to_excel("test.xlsx")

I want to change the color of the headers in list1 to get something like this:

Expected Output

It can be the font or background color, but it must be changed with pandas.


Solution

  • A possible option :

    # df.insert(0, "Year", [2021, 2022, 2023]) to match your example!
    
    (
        df.style.apply_index(
            lambda x: np.where(
        x.isin(list1), "background-color: #8db4e2", ""),axis=1)
        #.to_excel("...", index=False) # uncomment to make an Excel
    )
    

    enter image description here