Pandas.to_markdown() in Pandas



Pandas to_markdown Method

Pandas to_markdown() function converts a DataFrame or Series into a Markdown-formatted table, which is incredibly useful for generating reports or sharing data with colleagues.

Syntax : pandas.to_markdown()

Return : Return the markdown table.

Using Pandas.to_markdown()

Using to_markdown() is incredibly simple. You first need to import pandas:

import pandas as pd

Then you can use the function on a DataFrame or Series:

df = pd.read_csv("data.csv")
print(df.to_markdown())

This will print out a Markdown-formatted table of your DataFrame:

|    |   Column 1 | Column 2   |
|---:|-----------:|:-----------|
|  0 |          1 | a          |
|  1 |          2 | b          |
|  2 |          3 | c          |
|  3 |          4 | d          |
|  4 |          5 | e          |
|  5 |          6 | f          |

Customizing to_markdown()

to_markdown() also allows for customizing the output, such as changing the column headers:

df = pd.read_csv("data.csv")
print(df.rename(columns={"Column 1": "New Column Name"}).to_markdown())

This will produce a table with the new column name:

|    |   New Column Name   | Column 2   |
|---:|------------------:|:-----------|
|  0 |                 1 | a          |
|  1 |                 2 | b          |
|  2 |                 3 | c          |
|  3 |                 4 | d          |
|  4 |                 5 | e          |
|  5 |                 6 | f          |

Other customization options include changing the index name, hiding the index column, and specifying the table format.

Example #1 : Using to_markdown() to customize the table formatting

 
import pandas as pd

# create sample DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Salary': [50000, 60000, 70000]
})

# convert DataFrame to markdown with custom formatting
markdown = df.to_markdown(
    index=False,
    floatfmt='.2f',
    headers=['Employee Name', 'Age (years)', 'Annual Salary (USD)']
)

print(markdown)


| Employee Name | Age (years) | Annual Salary (USD) |
|---------------|------------|---------------------|
| Alice         | 25.00      | 50000.00            |
| Bob           | 30.00      | 60000.00            |
| Charlie       | 35.00      | 70000.00            |

In this example, we’ve used the index, floatfmt, and headers arguments to customize the table formatting. The index argument is set to False to exclude the row index from the output. The floatfmt argument specifies that floating-point numbers should be formatted with two decimal places. Finally, the headers argument is used to rename the columns.

Another Example

 
import pandas as pd

# Create a sample dataframe
data = {'Name': ['John', 'Jane', 'David', 'Maria', 'James'],
        'Age': [25, 30, 40, 35, 28],
        'City': ['New York', 'Paris', 'London', 'Sydney', 'Tokyo']}
df = pd.DataFrame(data)

# Add a new column to the dataframe
df['Salary'] = [50000, 75000, 100000, 90000, 60000]

# Use to_markdown() to format the dataframe as a markdown table
markdown_table = df.to_markdown(index=False)

# Print the markdown table
print(markdown_table)


In this example, we first create a sample dataframe with information about five individuals, including their names, ages, and cities. We then add a new column to the dataframe for their salaries.

Next, we use the to_markdown() function to format the dataframe as a markdown table, without including the row index. Finally, we print the resulting markdown table to the console.

This example demonstrates how the to_markdown() function can be used to easily format a Pandas dataframe as a markdown table, making it easy to display and share the data in a clear, organized way.

Last Updated on May 12, 2023 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs