So, Let's say I have outputs of the following form:
How would one insert this output into latex? I have tried using verbatim but I didn't like the result I wanted.
So, Let's say I have outputs of the following form:
How would one insert this output into latex? I have tried using verbatim but I didn't like the result I wanted.
If you control the print statements creating the current output then you can also write print statements to generate LaTeX code. Simple example:
Python:
headers = ["x 1","x 2","x 3","x 4","x 5","bbar"]
data = dict()
data["x 4"] = [1,2,3,1,0,9]
data["x 5"] = [3,2,2,0,1,15]
data["z"] = [1,9,3,0,0,0]
textabular = f"l|{'r'*len(headers)}"
texheader = " & " + " & ".join(headers) + "\\"
texdata = "\hline\n"
for label in sorted(data):
if label == "z":
texdata += "\hline\n"
texdata += f"{label} & {' & '.join(map(str,data[label]))} \\\n"
print("\begin{tabular}{"+textabular+"}")
print(texheader)
print(texdata,end="")
print("\end{tabular}")
Generated LaTeX code:
\begin{tabular}{l|rrrrrr}
& x 1 & x 2 & x 3 & x 4 & x 5 & bbar\\
\hline
x 4 & 1 & 2 & 3 & 1 & 0 & 9 \\
x 5 & 3 & 2 & 2 & 0 & 1 & 15 \\
\hline
z & 1 & 9 & 3 & 0 & 0 & 0 \\
\end{tabular}
Output:
data dictionary and then the code below, unchanged, will generate the second table. Depending on how complex your data is you might need to add in some extra Python logic.
– Marijn
Jan 26 '22 at 21:09
pythontex; I use the sagetex package for Python (plus a CAS). See here or here for some examples. I would think pythontex can do this as well.
– DJP
Jan 26 '22 at 22:45
f"" I guess), I decided not to spend too much effort on making the Python code clean and readable :)
– Marijn
Jan 27 '22 at 06:49
r and f work together but you are right it may not be worth the effort :). I understand I am probably in the wrong place pointing at something of little importance but I always consider using r"" to avoid multiple backslashes.
– Celdor
Jan 27 '22 at 08:37
Expanding on the above answers that use print statements for generating the Latex code: there is a Python library called latextable for doing exactly this https://github.com/JAEarly/latextable
There's also guidance on how to use it here: https://towardsdatascience.com/how-to-create-latex-tables-directly-from-python-code-5228c5cea09a
Full disclosure - I am the author of this library.