Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

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:
Col1Col2
r10a
r21b
r32c
Output LaTeX table is:\begin{tabular}{lrl}\toprule & Col1 & Col2 \\\midruler1 & 1 & a \\r2 & 2 & b \\r3 & 3 & c \\\bottomrule\end{tabular}

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:
Col1Col2
r10a
r21b
r32c
Output LaTeX table is:\begin{tabular}{rl}\topruleCol1 & Col2 \\\midrule1 & a \\2 & b \\3 & c \\\bottomrule\end{tabular}

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_1Col_2
00a
11b
22c
Output LaTeX table with formatting:\begin{tabular}{rl}\topruleCol_1 & Col_2 \\\midrule0.0 & A \\1.0 & B \\2.0 & C \\\bottomrule\end{tabular}

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:
Col1Col2
r10a
r21b
r32c
Output LaTeX table is:\begin{table}\caption{Integers and Alphabets with index}\label{tab:From_Pandas_DataFame}\begin{tabular}{lrl}\toprule & Col1 & Col2 \\\midruler1 & 1 & a \\r2 & 2 & b \\r3 & 3 & c \\\bottomrule\end{tabular}\end{table}
python_pandas_io_tool.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp