Skip to content

Instantly share code, notes, and snippets.

@blakete
Last active April 30, 2025 19:38
Show Gist options
  • Save blakete/c2ab23b928281c3678f0cf2a942b8e5b to your computer and use it in GitHub Desktop.
Save blakete/c2ab23b928281c3678f0cf2a942b8e5b to your computer and use it in GitHub Desktop.
Numpy Array to LaTeX Table
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