1

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.

3
  • @NicoCaldo I already saw this before posting but I struggled with applying the solution given there. I would still consider myself quite the beginner. Commented May 3, 2022 at 9:05
  • Can you explian more what not working? Commented May 3, 2022 at 9:20
  • Solution was wrongly reopened - stackoverflow.com/questions/62783783/… Commented May 3, 2022 at 9:42

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

11 Comments

Why you reopen question?
Why not post answer to dupe?
applymap_index a dupe?
cells / rows are not headers, no? I don't understand how your link solves the OP problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.