Skip to content

Instantly share code, notes, and snippets.

@tpaschalis
Last active March 13, 2021 08:33
Show Gist options
  • Save tpaschalis/7a2943c2248b78b2558c457428086082 to your computer and use it in GitHub Desktop.
Save tpaschalis/7a2943c2248b78b2558c457428086082 to your computer and use it in GitHub Desktop.
Convert a Numpy ndarray to LaTeX table/tabular environment.
import numpy as np
def np2lat(A):
filename = 'table.tex'
f = open(filename, 'a')
cols = A.shape[1]
# Change alignment and format of your output
tabformat = '%.3f'
tabalign = 'c'*cols
f.write('\n\\begin{table}[h]\n')
f.write('\\centering\n')
f.write('\\begin{tabular}{%s}\n' %tabalign)
# Use some numpy magic, just addding correct delimiter and newlines
np.savetxt(f, A, fmt=tabformat, delimiter='\t&\t', newline='\t \\\\ \n')
f.write('\\end{tabular}\n')
f.write('\\end{table}\n')
f.flush()
f.close() # When you leave a nested block, Python automatically calls f.close(), but in other case, it's safe to include
M = np.array([[12, 5, 2], [20, 4, 8], [ 2, 4, 3], [ 7, 1, 10]])
np2lat(M)
@OlivelliAri
Copy link

OlivelliAri commented Jun 22, 2019

Hi,
First of all thanks for sharing this.

I'm trying to use your function, but I keep on getting back an empty .txt file. Do you have any idea what could be going wrong there? I'm just trying with the same code as above.

Cheers,
Ari

@tpaschalis
Copy link
Author

tpaschalis commented Jun 24, 2019

@OlivelliAri Hi! Sorry for taking too long to get back to you.

Are you using the gist itself, or a modified version of the code? What version of numpy are you using? You can check this out by running print(numpy.version.version), as I think np.savetxt() was introduced around v1.10.

If the result returns an empty file, it might be the case of either wrong permissions on the file, or the function not exiting correctly, and the file not being closed (eg. if it is not part of a nested block). I have added two more lines to f.flush() and f.close() the file. Can you check with these two lines and tell me what the result is?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment