Plu*_*ile 7 python dataframe pandas pandas-styles
如何将 pandas 数据框设置为 Excel 表格(替代行颜色)?
样品样式:
样本数据:
import pandas as pd
import seaborn as sns
df = sns.load_dataset("tips")
Run Code Online (Sandbox Code Playgroud)
tdy*_*tdy 11
如果您的最终目标是保存to_excel,导出后保留样式的唯一方法是使用apply基于 - 的方法:
df.style.apply/是与/df.style.applymap对应的样式,并且工作方式类似df.applydf.applymapdf.style.apply_index/df.style.applymap_index是索引样式对应项(需要 pandas 1.4.0+)对于给定的示例,使用df.style.apply交替行颜色来设置每列的样式,并df.style.applymap_index设置所有行/列索引的样式:
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')
Run Code Online (Sandbox Code Playgroud)
如果您只关心 Jupyter 中的外观,另一个选择是使用(需要 pandas 1.2.0+)设置目标选择器的属性:df.style.set_table_styles
# pandas 1.2.0+
df.style.set_table_styles([
{'selector': 'tr:nth-child(even)', 'props': css_alt_rows},
{'selector': 'th', 'props': css_indexes},
])
Run Code Online (Sandbox Code Playgroud)