2013-01-17 118 views
30

一個LaTeX表是否有一個簡單的方法來導出數據幀(或它甚至部分)對乳膠?出口從熊貓數據框中

我在谷歌搜索,並只能夠使用asciitables方案尋找。

+0

除了這裏的答覆,這個問題有一個有趣的方法了。導出爲CSV格式,然後導入CSV到乳膠:http://tex.stackexchange.com/questions/54990/convert-numpy-array-into-tabular –

回答

54

DataFrames有to_latex方法:

In [42]: df = pd.DataFrame(np.random.random((5, 5))) 

In [43]: df 
Out[43]: 
      0   1   2   3   4 
0 0.886864 0.518538 0.359964 0.167291 0.940414 
1 0.834130 0.022920 0.265131 0.059002 0.530584 
2 0.648019 0.953043 0.263551 0.595798 0.153969 
3 0.207003 0.015721 0.931170 0.045044 0.432870 
4 0.039886 0.898780 0.728195 0.112069 0.468485 

In [44]: print df.to_latex() 
\begin{tabular}{|l|c|c|c|c|c|c|} 
\hline 
{} &   0 &   1 &   2 &   3 &   4 \\ 
\hline 
0 & 0.886864 & 0.518538 & 0.359964 & 0.167291 & 0.940414 \\ 
1 & 0.834130 & 0.022920 & 0.265131 & 0.059002 & 0.530584 \\ 
2 & 0.648019 & 0.953043 & 0.263551 & 0.595798 & 0.153969 \\ 
3 & 0.207003 & 0.015721 & 0.931170 & 0.045044 & 0.432870 \\ 
4 & 0.039886 & 0.898780 & 0.728195 & 0.112069 & 0.468485 \\ 
\hline 
\end{tabular} 

你可以簡單地寫一個TEX文件。

默認情況下,乳膠會呈現此爲:

as it would appear in latex

注:to_latex方法提供了多個配置選項。

+0

@hayden謝謝你的編輯 – bmu

+0

thx,工作!我只需要更新我的熊貓 – PlagTag

+0

''to_latex()'支持多索引? – TheChymera

4

只寫一個文本文件。這是什麼魔法:

import pandas as pd 
df = pd.DataFrame({"a":range(10), "b":range(10,20)}) 
with open("my_table.tex", "w") as f: 
    f.write("\\begin{tabular}{" + " | ".join(["c"] * len(df.columns)) + "}\n") 
    for i, row in df.iterrows(): 
     f.write(" & ".join([str(x) for x in row.values]) + " \\\\\n") 
    f.write("\\end{tabular}") 
+3

雖然它是有用的,以顯示它是多麼容易表格數據導出到使用普通Python的LaTeX,在這種情況下使用現有的工具,比如'DataFrame.to_latex()'當然好多了。 –

+2

嗨,我完全同意。我的理由是:1。 我開始與熊貓0.9版本,其中to_latex不可用之前 2.需要一些adjustement或有人想導出爲其他格式,如XAML,自定義XML或什麼時,這可能是有用的。 但是,謝謝你的評論 –