J4y
J4y

Reputation: 649

How do I change python pandas LaTeX output formatting?

I'm trying to better format my pandas dataframe output.

I have a series, which I then convert to a dataframe and then output to LaTeX.

meal.to_frame().to_latex('meal.tex')

This yields:

 \begin{tabular}{lr}
 \toprule
 {} &  count \\
 \midrule
 Meal    &        \\
 Spam    &  11723 \\
 Eggs    &   5865 \\
 \bottomrule
 \end{tabular}

How can I change the \toprule, \midrule, \bottomrule to be \hline. And how can I get the name of the index name model to appear as a column header? The end result I'm looking for is:

 \begin{tabular}{lr}
 \hline
 Meal    &  count \\
 \hline
 Spam    &  11723 \\
 Eggs    &   5865 \\
 \hline
 \end{tabular}

Upvotes: 1

Views: 2480

Answers (2)

Jer K
Jer K

Reputation: 895

The output of to_frame() is a string, so you can replace the \toprule, \midrule, and \bottomrule with \hline by:

print(df.to_latex(index=False).replace('\\toprule', '\\hline').replace('\\midrule', '\\hline').replace('\\bottomrule','\\hline'))

(assumes df is your pandas dataframe)

Setting index=False will remove the odd {} in the header of your first example.

Upvotes: 2

Tiemen Schuijbroek
Tiemen Schuijbroek

Reputation: 79

You could try working with tabulate https://pypi.python.org/pypi/tabulate. I use it for my Python projects all the time. You have two different LaTeX styles. But it's output is just a string with the LaTeX code, so you could always use a custom function to replace some parts.

If that doesn't work, try something else than the to_frame method. You could get the data with as_matrix(), add your labels and go from there.

For really custom styling you would need to write a simple script to build your string together yourself.

Upvotes: 0

Related Questions