将pandas中的单独列对齐到latex

10

我正在使用 pandasto_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个回答

12

到目前为止(pandas版本0.17.1),to_latex方法已经有了column_format参数,因此您可以简单地执行以下操作:

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

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')

或者更通用地使用正则表达式进行替换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接