
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Python Pandas to_latex() Method
Theto_latex() method in Python's Pandas library allows you to convert the Pandas objects, such as DataFrame, or Series, into a LaTeX tabular, longtable, or nested table formats.
This method is particularly useful for integrating tabular data from Pandas into LaTeX documents for scientific papers, reports, or presentations. This method requires\usepackage{{booktabs}}.
The generated LaTeX code can either be directly copied into a LaTeX document or saved to a file and included using\input{{table.tex}}.
Syntax
Following is the syntax of the Python Pandas to_latex() method −
DataFrame.to_latex(buf=None, *, columns=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, decimal='.', multicolumn=None, multicolumn_format=None, multirow=None, caption=None, label=None, position=None)
When using theto_latex() method on aSeries object, you should call it asSeries.to_latex().
Parameters
The Python Pandas to_latex() method accepts the below parameters −
buf − This parameter accepts a string, path object, or StringIO-like object, representing where buffer to write to. Returns a string if set to None.
columns: Specifies a subset of columns to include in the output. By default, it includes all columns.
header: Write out column names. This parameter takes a boolean or list of strings indicating custom column headers.
index: Specifies including or excluding row indices in the output. Defaults to True.
na_rep: Representation for missing data (e.g., 'NaN').
formatters: Formatter functions or a dictionary of formatters to apply to specific columns.
float_format: String format for floating-point numbers.
sparsify: An optional boolean parameter, set to False for a DataFrame with a hierarchical index to print every multiindex key at each row.
index_names: Prints the names of the indexes. By default set to True.
bold_rows: By setting it True you can make the row labels bold in the output LaTeX.
column_format: LaTeX format string for columns (e.g., 'rcl' for 3 columns).
longtable: Use alongtable environment. Requires\usepackage{longtable} in the preamble.
escape: Escape special LaTeX characters in the data.
caption: Caption for the table. Can be a string or a tuple of (full_caption, short_caption).
label: Label for referencing the table in LaTeX documents using\ref.
Return Value
The Pandasto_latex() method returnsNone if the output is written to a buffer or file. Otherwise, returns a LaTeX-formatted string.
Example: Converting a Pandas Series to LaTeX
This example converts a Pandas Series object into a LaTeX using theSeries.to_latex() method.
import pandas as pd# Creating a Pandas Seriess = pd.Series([1, 2, 3, 4], index=["cat", "dog", "fish", "mouse"])# Display the Input Seriesprint("Original Series:")print(s)# Convert DataFrame to LaTeX formatlatex_output = s.to_latex()print("\nOutput LaTeX table:")print(latex_output)The output of the above code is as follows −
Original Series:cat 1dog 2fish 3mouse 4dtype: int64Output LaTeX table:\begin{tabular}{lr}\toprule & 0 \\\midrulecat & 1 \\dog & 2 \\fish & 3 \\mouse & 4 \\\bottomrule\end{tabular}Example: Converting a DataFrame to LaTeX Table
This example demonstrates saving a Pandas DataFrame object into a LaTex table using theDataFrame.to_latex() method.
import pandas as pd# Create a DataFramedf = pd.DataFrame({"Col1": [1, 2, 3], "Col2": ["a", "b", "c"]}, index=["r1", "r2", "r3"])print("Original DataFrame:")print(df)# Convert DataFrame to LaTeX formatlatex_output = df.to_latex()print("\nOutput LaTeX table is:")print(latex_output)When we run above program, it produces following result −
Original DataFrame:
| Col1 | Col2 | |
|---|---|---|
| r1 | 0 | a |
| r2 | 1 | b |
| r3 | 2 | c |
Example: Converting DataFrame Without Index
This example converts a Pandas DataFrame object into a LaTeX without index by setting theindex=False in theto_latex() method.
import pandas as pd# Create a DataFramedf = pd.DataFrame({"Col1": [1, 2, 3], "Col2": ["a", "b", "c"]}, index=["r1", "r2", "r3"])print("Original DataFrame:")print(df)# Convert DataFrame to LaTeX formatlatex_output = df.to_latex(index=False)print("\nOutput LaTeX table is:")print(latex_output)Following is an output of the above code −
Original DataFrame:
| Col1 | Col2 | |
|---|---|---|
| r1 | 0 | a |
| r2 | 1 | b |
| r3 | 2 | c |
Example: Converting a DataFrame to LaTeX Table with Formatting
This example converts a DataFrame object into the LaTeX Table with formatting. Here we will apply a float converter function for the first column andstring.upper() function for the second column.
import pandas as pd# Create a DataFramedf = pd.DataFrame({"Col_1": range(3), "Col_2": ['a', 'b', 'c']})print("Original DataFrame:")print(df)# Convert DataFrame to LaTeX formatlatex_output = df.to_latex(index=False, formatters={"Col_2": str.upper, "Col_1": float})print("\nOutput LaTeX table with formatting:")print(latex_output)On executing the above program, you will get the following result −
Original DataFrame:
| Col_1 | Col_2 | |
|---|---|---|
| 0 | 0 | a |
| 1 | 1 | b |
| 2 | 2 | c |
Example: Adding Caption and Label to LaTeX Table
The following example demonstrates how to add a caption and label while converting DataFrame to LaTeX using theto_latex() method.
import pandas as pd# Create a DataFramedf = pd.DataFrame({"Col1": [1, 2, 3], "Col2": ["a", "b", "c"]}, index=["r1", "r2", "r3"])print("Original DataFrame:")print(df)# Convert DataFrame to LaTeX with a Caption and Labellatex_output = df.to_latex(caption="Integers and Alphabets with index", label="tab:From_Pandas_DataFame")print("\nOutput LaTeX table is:")print(latex_output)Following is an output of the above code −
Original DataFrame:
| Col1 | Col2 | |
|---|---|---|
| r1 | 0 | a |
| r2 | 1 | b |
| r3 | 2 | c |