Last active
April 30, 2025 19:38
-
-
Save blakete/c2ab23b928281c3678f0cf2a942b8e5b to your computer and use it in GitHub Desktop.
Numpy Array to LaTeX Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
def numpy_to_latex( | |
arr: np.ndarray, | |
columns=None, | |
index=False, | |
caption=None, | |
label=None, | |
float_format="%.3f", | |
**to_latex_kwargs | |
): | |
df = pd.DataFrame(arr, columns=columns) | |
latex_kwargs = { | |
"index": index, | |
"caption": caption, | |
"label": label, | |
"float_format": float_format, | |
**to_latex_kwargs | |
} | |
for key in ("caption", "label"): | |
if latex_kwargs.get(key) is None: | |
del latex_kwargs[key] | |
return df.to_latex(**latex_kwargs) | |
if __name__ == "__main__": | |
np.random.seed(0) | |
arr = np.random.randn(4, 3) | |
cols = ["Feature 1", "Feature 2", "Feature 3"] | |
latex_code = numpy_to_latex( | |
arr, | |
columns=cols, | |
caption="My random data", | |
label="tab:random", | |
column_format="lrrr", | |
longtable=True | |
) | |
print(latex_code) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment