Reputation: 288
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.
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
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
Upvotes: 4