对齐pandas to_latex中的各列

Sur*_*esh 8 python latex pandas

我正在使用该pandas to_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
Run Code Online (Sandbox Code Playgroud)

我的输出表如下所示:

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}
Run Code Online (Sandbox Code Playgroud)

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

目前是否支持?

Dan*_*ung 7

到目前为止(pandas版本0.17.1),该to_latex方法具有column_format参数,因此您可以这样做

print df.to_latex(index=None, column_format='rrr')
Run Code Online (Sandbox Code Playgroud)


404*_*pio 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')
Run Code Online (Sandbox Code Playgroud)

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