Squary94
Squary94

Reputation: 288

Apply background color to a row in excel using pandas in python

I have a simple test sheet and I want to give the title row a grey background color using pandas. After the change, save the result as a new file.

enter image description here

I tried to use the following code.

df_test = pd.read_excel(r'...\test.xlsx')
df_test = df_test.loc[1:1].style.apply('background-color: grey', axis = 1)
df_test.to_excel(r'...\test_1.xlsx', sheet_name='asdf', index = False)

But I only receive AttributeError: 'background-color : grey' is not a valid function for 'DataFrame' object. I already tried a few other variations of this to no avail.

Upvotes: 1

Views: 2531

Answers (1)

Corralien
Corralien

Reputation: 120391

You can use Styler.applymap_index

def bg_header(x):
    return "background-color: grey"
    
df.style.applymap_index(bg_header, axis=1).to_excel('output.xlsx', index=False)

Note: you need Pandas>=1.4.0

enter image description here

Upvotes: 4

Related Questions