2015-08-28 62 views
3

我正在使用Python Pandas。LaTeX輸出的Python Pandas中的Midrule

我想從Excel工作簿中自動創建LaTeX表。我到目前爲止有腳本完成創建以下數據框:

  Date  Factor A Factor B Total 
Person A 01/01/2015 A   C   $220m 
Person B 01/02/2015 B   D   $439m 
            Total  $659m 

我可以用熊貓.to_latex()命令從這個創建booktabs表,這是所有罰款。

我的問題是,是否有可能在LaTeX輸出上面的數據框的最後一行之前添加一個midrule?

+0

正如[docs ](http://pandas.pydata.org/pandas-docs/version/0.15.1/generated/pandas.DataFrame.to_latex.html)'.to_latex()'返回一個字符串。你能否把這個字符串添加到你的問題中? – albert

回答

5

由於大熊貓.to_latex()似乎並不被一些字符串處理手動提供這樣的選擇我會這樣:

import pandas as pd 
import numpy as np 

# use a DataFrame df with some sample data 
df = pd.DataFrame(np.random.random((5, 5))) 

# get latex string via `.to_latex()` 
latex = df.to_latex() 

# split lines into a list 
latex_list = latex.splitlines() 

# insert a `\midrule` at third last position in list (which will be the fourth last line in latex output) 
latex_list.insert(len(latex_list)-3, '\midrule') 

# join split lines to get the modified latex output string 
latex_new = '\n'.join(latex_list) 

乳膠輸出,無需額外\midrule

\begin{tabular}{lrrrrr} 
\toprule 
{} &   0 &   1 &   2 &   3 &   4 \\ 
\midrule 
0 & 0.563803 & 0.962439 & 0.572583 & 0.567999 & 0.390899 \\ 
1 & 0.728756 & 0.452122 & 0.358927 & 0.426866 & 0.234689 \\ 
2 & 0.907841 & 0.622264 & 0.128458 & 0.098953 & 0.711350 \\ 
3 & 0.338298 & 0.576341 & 0.625921 & 0.139799 & 0.146484 \\ 
4 & 0.303568 & 0.495921 & 0.835966 & 0.583697 & 0.675465 \\ 
\bottomrule 
\end{tabular} 

輸出,帶手動添加\midrule

\begin{tabular}{lrrrrr} 
\toprule 
{} &   0 &   1 &   2 &   3 &   4 \\ 
\midrule 
0 & 0.563803 & 0.962439 & 0.572583 & 0.567999 & 0.390899 \\ 
1 & 0.728756 & 0.452122 & 0.358927 & 0.426866 & 0.234689 \\ 
2 & 0.907841 & 0.622264 & 0.128458 & 0.098953 & 0.711350 \\ 
3 & 0.338298 & 0.576341 & 0.625921 & 0.139799 & 0.146484 \\ 
\midrule 
4 & 0.303568 & 0.495921 & 0.835966 & 0.583697 & 0.675465 \\ 
\bottomrule 
\end{tabular}