使用 python 中的 pandas 将背景色应用于 excel 中的一行

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

我有一个简单的测试 sheet,我想使用 pandas 为标题行提供灰色背景色。更改后,将结果另存为新文件。

我尝试使用以下代码。

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)

但我只收到AttributeError: 'background-color : grey' is not a valid function for 'DataFrame' object。我已经尝试了其他一些变体,但都无济于事。

您可以使用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)

注意:您需要Pandas>=1.4.0