2

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} 

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.