How to get a latex table of sympy expressions in i

2019-03-30 15:28发布

问题:

I'm using sympy to collect terms from several expressions and would like to format the results (within ipython-notebook) in a table with the terms down the left most column and each subsequent column representing one expression. The entries in the column are from the dict returned by sympy.collect(syms, evaluate=False)

So far I have:

from IPython.display import display, Latex
import pandas as pd
import sympy as sym
sym.init_printing()
x,y,z = sym.symbols('x,y,z')
da,db,dc = sym.symbols('{\Delta}a {\Delta}b {\Delta}c ' )

e_list = []
d_list = []
e_list.append(da*2*x + da*(y - 2) + db*3*z + dc*(x+y))
e_list.append(dc*z + dc*x + da*x + db*(z+2))
for e in e_list:
    display(e.expand().collect((x,y,z)))
    d_list.append(e.expand().collect((x,y,z),evaluate=False))

df = pd.DataFrame(d_list).T

The dataframe displays as I would like except the entries are in raw latex.

I though the following would work:

Latex(df.to_latex())

but all I get is the latex code surrounded by a box.

EDIT: This seems to be a known problem with ipython and latex tables, see here:

http://grokbase.com/t/scipy.org/ipython-user/12acr5rrr1/may-be-old-topic-just-getting-started-with-ipython-notebook-trouble-with-tables

I've got two different workarounds. Use unicode:

sym.init_printing(use_latex=False)
...
da,db,dc = sym.symbols('∆a ∆b ∆c' )

Or display the table as a sympy matrix:

terms = [x,y,z]
d_list = [(e.expand().collect((terms),evaluate=False)) for e in e_list]
mterms = sym.zeros(M.shape[0],len(terms)+1)
key1 = d_list[0].keys()[0]
terms.insert(0,key1)
for i in range(mterms.shape[0]):
    for j in range(mterms.shape[1]):
        try:
            mterms[i,j] = d_list[i][terms[j]]
        except:
            mterms[i,j] = 0

mterms

回答1:

Undoubtedly, part of the problem is that the latex you get out of df.to_latex() is not actually valid latex. For example, if you just take the output of that function and paste it into a dedicated latex document, it won't compile.

In particular, some of the entries in the table contain things like \Delta, but these are outside of a math environment (no dollar signs).

So that's definitely a problem. Another possible problem is the use of \toprule, etc. Those are non-standard latex constructions (though they can be used with the right latex package), but I don't know if those rules are recognized by the Latex function.

All of that said, I can't even get the simplest tabular environment to display properly. For example, even if I do

Latex(r"""\begin{tabular}{l} 1 \\ 2 \end{tabular}""")

I get a boxed result, just as you say. (Though the contents of that string do compile properly in a dedicated latex document.)