PANDAS DataFrame Styler-如何将Pandas DataFrame作为Excel表样式?
如何将熊猫数据框架作为excel表(替代行颜色)样式?
示例样式:
示例数据:
import pandas as pd
import seaborn as sns
df = sns.load_dataset("tips")
How to style the pandas dataframe as an excel table (alternate row colour)?
Sample style:
Sample data:
import pandas as pd
import seaborn as sns
df = sns.load_dataset("tips")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的最终目标是保存
to_excel
,导出后保留样式的唯一方法是使用基于apply
的方法:df.style.apply
/df.style.applymap
是df.apply
/df.applymap
的样式对应项,工作方式类似df.style.apply_index
/df.style.applymap_index
是索引样式对应项(需要 pandas 1.4.0+)对于给定的示例,请使用
df.style.apply
使用交替的行颜色和df.style.applymap_index
设置所有行/列索引的样式:如果您只关心 Jupyter 中的外观,另一个选择是使用
df.style.set_table_styles
(需要 pandas 1.2.0+):If your final goal is to save
to_excel
, the only way to retain the styling after export is using theapply
-based methods:df.style.apply
/df.style.applymap
are the styling counterparts todf.apply
/df.applymap
and work analogouslydf.style.apply_index
/df.style.applymap_index
are the index styling counterparts (requires pandas 1.4.0+)For the given sample, use
df.style.apply
to style each column with alternating row colors anddf.style.applymap_index
to style all row/col indexes:If you only care about the appearance in Jupyter, another option is to set properties for targeted selectors using
df.style.set_table_styles
(requires pandas 1.2.0+):