如何为pandas的DataFrame添加自定义标题 以一月日历表格为例
解决方案
直接调用pandas Styler内置的set_caption()方法即可为表格添加标题,你原有代码仅需在链式调用最后追加该方法即可,修改后的完整代码如下:
import pandas as pd January= [['','','','','',1 ,2],[t for t in range(3,10)],[t for t in range(10,17)],[t for t in range(17,24)], [t for t in range(24,31)],[31,'','','','','','']] df = pd.DataFrame(January, columns=['Mo','Di','Mi','Do','Fr','Sa','So']) df.style.hide_index()\ .set_table_styles([ {'selector' : '','props' : [('border','1px solid black')]}, # 可选:添加标题的样式配置,不需要可以删掉这段 {'selector': 'caption', 'props': [ ('font-weight', 'bold'), ('font-size', '18px'), ('margin-bottom', '6px'), ('text-align', 'center') ]} ])\ .set_caption("January")
如果不需要调整标题的默认样式,直接追加.set_caption("January")即可,不需要额外修改表格样式配置。
内容的提问来源于stack exchange,提问作者Claudio
相关产品推荐
相关产品推荐

