对齐pandas to_latex中的各列

时间:2014-06-15 14:54:20

标签: python pandas latex

我正在使用pandas to_latex方法将数据框转换为latex tabular。我没有看到更改结果表格的对齐字段的选项。例如,我有一个如下所示的数据框:

In [46]: df
Out[46]: 
    Number of days  Tuples Distinct Tuples
162             29  700587           41300
163             20  497599           29302
164             15  365599           21382
165             10  256903           14916
166              5  127647            7441
167              2   54254            3117
168              1   26987            1288

我的输出表如下所示:

In [50]: print df.to_latex(index=None)
\begin{tabular}{lll}
\toprule
Number of days &  Tuples & Distinct Tuples \\
\midrule
            29 &  700587 &           41300 \\
            20 &  497599 &           29302 \\
            15 &  365599 &           21382 \\
            10 &  256903 &           14916 \\
             5 &  127647 &            7441 \\
             2 &   54254 &            3117 \\
             1 &   26987 &            1288 \\
\bottomrule
\end{tabular}

我想要的是{lll}路线更改为{rrr}。一般来说,我甚至可能想要不同列的不同对齐,甚至使用垂直分隔符在{r|r|r}指示符中。

目前是否支持?

2 个答案:

答案 0 :(得分:6)

到目前为止(pandas版本0.17.1),to_latex方法具有column_format参数,因此您只需执行

print df.to_latex(index=None, column_format='rrr')

答案 1 :(得分:5)

正如您在pandas代码中看到的(此函数用于渲染latex_table): https://github.com/pydata/pandas/blob/master/pandas/core/format.py#L492 目前还不支持。只有当您的数据是numpy的数字时,它才会被格式化为正确。在python中,您可以很容易地格式化列。

print df.to_latex(index=None).replace('lll','rrr')

或以更通用的方式使用正则表达式替换。

相关问题