20

I've read about the to_latex method, but it's not clear how to use the formatters argument.

I have some numbers which are too long and some which I want thousand separators.

A side issue for the to_latex method on multi-indexed tables, the indices are parsed together and it issues some &s in the latex output.

1
  • From the answer below you can search for python formatting functions (too long has been mentioned, and perhaps see here for thousand separators). Commented Feb 25, 2013 at 15:56

1 Answer 1

29

For a simple data frame. First, without formatters:

In [11]: df Out[11]: c1 c2 first 0.821354 0.936703 second 0.138376 0.482180 In [12]: print df.to_latex() \begin{tabular}{|l|c|c|c|} \hline {} & c1 & c2 \\ \hline first & 0.821354 & 0.936703 \\ second & 0.138376 & 0.482180 \\ \hline \end{tabular} 

Copy-pasting the output (of [12]) to latex, we get: latex without formatters

If we create two functions f1 and f2 and put them into to_latex as formatters:

def f1(x): return 'blah_%1.2f' % x def f2(x): return 'f2_%1.2f' % x In [15]: print df.to_latex(formatters=[f1, f2]) \begin{tabular}{|l|c|c|c|} \hline {} & c1 & c2 \\ \hline first & blah\_0.82 & f2\_0.94 \\ second & blah\_0.14 & f2\_0.48 \\ \hline \end{tabular} 

Copy-pasting the output to latex, we get: latex with formatters f1 and f2

Note: how the formatter function f1 is applied to the first column and f2 to the second.

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

2 Comments

I have written code to handle the following issues: * Pandas Multi-indexes * handling latex reserved characters in the table. Standard pandas method leads to errors in latex compiling if '&', '%', '$', '#' etc are used in any of the cells. they need to be escaped * also written code that can band the latex representation of the pandas dataframe (shading alternate rows) * also autoformatting numbers Methods are tied up in in latex generating class that 'n wrote so difficult to post here as code is bit messy. I am happy to post here if anyone need some help.
If you want to format only float columns, set the float_format parameter to your format function. You don't need to create a list of functions for that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.