Programmatically convert pandas dataframe to markdown table

Given a pandas dataframe, we have to programmatically convert pandas dataframe to markdown table. By Pranit Sharma Last updated : September 30, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Converting pandas dataframe to markdown table

To programmatically convert pandas DataFrame to markdown table, we will directly use DataFrame.to_markdown() method. It is used to print DataFrame in Markdown-friendly format.

The syntax of the DataFrame.to_markdown() method is:

DataFrame.to_markdown(buf=None, mode='wt', index=True, storage_options=None, **kwargs)

Let us understand with the help of an example,

Python program to programmatically convert pandas dataframe to markdown table

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'id':[1,2,3,4,5],
    'Name':['Raghu','Rajiv','Ranvijay','Prince','Nikhil'],
    'age':[40,40,38,33,40],
    'location':['Mumbai','Mumbai','Cgandigarh','Amritsar','Delhi'],
    'salary':[12000,12000,15000,14000,15000],
    'in-hand':[10000,10000,13500,12500,13500],
    'sex':['male','male','male','male','male']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Displaying the data in markdown table format
print(df.to_markdown())

Output

The output of the above program is:

Example: Programmatically convert pandas dataframe to markdown table

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.