如何使用pandas Dataframe.to_latex()为LaTeX表格添加全局配置及自定义分隔线
解决方案
直接使用pandas.io.formats.style.Styler.to_latex()即可实现所有需求,不需要手动修改输出的LaTeX代码,也不需要使用formatters参数做复杂适配。
步骤1:构造示例DataFrame
import pandas as pd data = { 'F-1': {('H', 'Baseline'): 0.9044961552465764, ('H', 'Fine-Tuned'): 0.9387767951280728, ('S', 'Baseline'): 0.547968262581014, ('S', 'Fine-Tuned'): 0.5815634664656218, ('G', 'Baseline'): 0.8793941208568047, ('G', 'Fine-Tuned'): 0.9102870296052078, ('T', 'Baseline'): 0.9110316123313993, ('T', 'Fine-Tuned'): 0.9404444309041384}, 'F-2': {('H', 'Baseline'): 0.8865304318012182, ('H', 'Fine-Tuned'): 0.9273671656403047, ('S', 'Baseline'): 0.5063582247873787, ('S', 'Fine-Tuned'): 0.5408162758046822, ('G', 'Baseline'): 0.8551648617281388, ('G', 'Fine-Tuned'): 0.8947135188980437, ('T', 'Baseline'): 0.8774834363467384, ('T', 'Fine-Tuned'): 0.9134634736945935} } df = pd.DataFrame(data).rename_axis(['Dataset', 'Model'])
步骤2:实现基础自定义全局配置
可直接通过参数控制是否添加\footnotesize、\centering,代码如下:
styler = df.style # 保留3位小数 styler = styler.format(precision=3) latex_code = styler.to_latex( caption="Caption of the table.", label="tab:06_01.example", position="H", # 配置table浮动参数 position_float="centering", # 自动添加\centering,不需要直接删除该参数即可 hrules=True, # 自动使用booktabs包的\toprule、\midrule、\bottomrule column_format="lrrr", # 自定义列格式 preamble="\\footnotesize\n" # 自动添加\footnotesize,不需要直接删除该参数即可 )
步骤3:实现自定义位置插入分隔线
如果需要在指定数据集(比如S)之后插入\midrule,仅需要额外调用append_midrule方法指定插入位置即可:
styler = df.style.format(precision=3) # 示例中S数据集占2行,排在H(2行)之后,所以在第4行(索引从0开始)后插入分隔线 styler = styler.append_midrule(position=4) latex_code = styler.to_latex( caption="Caption of the table.", label="tab:06_01.example", position="H", position_float="centering", hrules=True, column_format="lrrr", preamble="\\footnotesize\n" )
说明
DataFrame.to_latex()的formatters参数仅用于格式化单元格内容,无法实现全局配置插入、自定义横线的需求,Styler.to_latex()是针对这类高度自定义LaTeX表格场景的官方推荐方案,所有参数均可批量配置,适合批量生成表格的场景。
内容的提问来源于stack exchange,提问作者MrT77
相关产品推荐
相关产品推荐

