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