熊猫Styler对象是一个独立的对象df
它创造了它。要将样式化的 DataFrame 写出到 Excel,我们需要使用实际的 Styler 对象,而不是df
。最简单的方法是使用Styler.to_excel:
# Save Styler Object for Later
styler = df.style
# Apply Styles (This can be chained or on separate lines)
styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
styler.apply(color, axis=1)
# Export the styler to excel
styler.to_excel('Output.xls', index=False)
方法链也有效:
df.style \
.applymap(lambda x: 'background-color : yellow' if x > 1 else '') \
.apply(color, axis=1) \
.to_excel('Output.xls', index=False)
*Note: index=False
确保 DataFrame 索引不包含在输出中。 (“从 0 开始的附加行枚举”)
我们还可以使用pd.ExcelWriter与Styler以类似的方式:
# Save Styler Object for Later
styler = df.style
# Apply Styles (This can be chained or on separate lines)
styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
styler.apply(color, axis=1)
with pd.ExcelWriter('Output.xls') as writer:
styler.to_excel(writer, index=False)
作为一般性改进,我们可以通过传递来在 DataFrame 级别设置样式axis=None
to 造型器应用并在一个函数中执行所有修改:
def color(df_):
styles_df = pd.DataFrame('', index=df_.index, columns=df_.columns)
# Color cells yellow where they are greater than 1
styles_df[df_ > 1] = 'background-color: yellow'
# Color rows red where there are any null values across rows
styles_df.loc[df.isnull().any(axis=1), :] = 'background-color: red'
return styles_df
with pd.ExcelWriter('Output.xls') as writer:
df.style.apply(color, axis=None).to_excel(writer, index=False)