如果你的最终目标是拯救to_excel
,导出后保留样式的唯一方法是使用apply
基于方法:
-
df.style.apply https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply.html / df.style.applymap https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.applymap.html是造型对应的
df.apply
/ df.applymap
并类似地工作
-
df.style.apply_index https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply_index.html / df.style.applymap_index https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.applymap_index.html是索引样式对应项(需要 pandas 1.4.0+)
对于给定的样本,使用df.style.apply https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply.html使用交替的行颜色设置每列的样式df.style.applymap_index https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.applymap_index.html设置所有行/列索引的样式:
css_alt_rows = 'background-color: powderblue; color: black;'
css_indexes = 'background-color: steelblue; color: white;'
(df.style.apply(lambda col: np.where(col.index % 2, css_alt_rows, None)) # alternating rows
.applymap_index(lambda _: css_indexes, axis=0) # row indexes (pandas 1.4.0+)
.applymap_index(lambda _: css_indexes, axis=1) # col indexes (pandas 1.4.0+)
).to_excel('styled.xlsx', engine='openpyxl')
如果您只关心 Jupyter 中的外观,另一个选项是使用以下命令设置目标选择器的属性df.style.set_table_styles https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_table_styles.html (需要 pandas 1.2.0+):
# pandas 1.2.0+
df.style.set_table_styles([
{'selector': 'tr:nth-child(even)', 'props': css_alt_rows},
{'selector': 'th', 'props': css_indexes},
])