Wednesday, January 9, 2013

Python Script for Transposing a Table in LaTeX

Sometimes you gotta try transposing a table in LaTeX, just to see if it looks better. It probably doesn't, but you gotta try. And it's a nasty job to be doing that by hand.

Try this:
(Download the .py file to keep that indentation right!)


#LaTeX table transpose
#Peter Raffensperger
#9 Jan 2012

import numpy

x = r"""
\hline
a & b & c & d & e\\
\hline
f & g & h & i & j \\
k & l & m & n & o \\
"""

x = x.replace(r'\hline', '')
tableRows = x.split(r'\\')
table = None
for i, t in enumerate(tableRows):
if t != '\n':
if table is None:
table = numpy.array(t.split('&'))
else:
table = numpy.vstack((table, numpy.array(t.split('&'))))

tableTrans = table.T.tolist()

tNew = ''
for row in tableTrans:
for col in row:
tNew += col.strip() + ' & '
tNew = tNew[:-2] + r' \\' + '\n'
print tNew

3 comments:

Unknown said...

Thanks, it works rather nicely!
A most helpful script.

For python 3 compatility it only needs a parenthesis after print. Not sure if compatible with 2.7 as well.

Unknown said...

Hi, I modified the code to use list comprehensions.

table = np.array([[c.strip() for c in r.split('&')] for r in x.replace(r'\hline', '').split(r'\\') if r!='\n'], dtype=object)

print((r' \\'+'\n').join(' & '.join(r) for r in table.T))

John F. Raffensperger said...

You can also copy & paste into Excel for its easy transpose function. Just has to be tab delimited.