Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

python - Export a LaTeX table from pandas DataFrame

Is there an easy way to export a data frame (or even a part of it) to LaTeX?

I searched in google and was only able to find solutions using asciitables.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

DataFrames have a to_latex (see the pandas docs) method:

>>> df = pd.DataFrame(np.random.random((5, 5)))
>>> df  
          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

>>> print(df.to_latex())
egin{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}

You can simply write this to a tex file.

By default latex will render this as:

as it would appear in latex

Note: the to_latex (see the pandas docs) method offers several configuration options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...