Pretty Print a Pandas Dataframe

In this article we will discuss how to print the a Dataframe in pretty formats.

Table of Contents

A DataFrame is a data structure that will store the data in rows and columns. We can create a DataFrame using pandas.DataFrame() method. Let’s create a dataframe with 4 rows and 4 columns

import pandas as pd

# Create a Dataframe for a Dictionary
df=pd.DataFrame({'id'   :[58,59,60,61],
                 'name' :['sravan','jyothika','preethi','srinadh'],
                 'age'  :[22,21,22,23],
                 'subjects':['java','php','sql','r/python']})

# Display the Dataframe
print(df)

Output:

   id      name  age  subjects
0  58    sravan   22      java
1  59  jyothika   21       php
2  60   preethi   22       sql
3  61   srinadh   23  r/python

Print Pandas Dataframe as Table

We are going to print the dataframe in tabular format using the following methods.

Advertisements

Using set_option() method

Here we are going to display the dataframe in tabular format using set_option() method. In this method we have to set the options given below. We have to use display() method to display the dataframe.

  • pd.set_option(‘display.max_rows’, n )
    • This option is used to set the maximum rows to be displayed. If we want to display the all rows , we have to specify as None in n parameter.
  • pd.set_option(‘display.max_columns’, n)
    • This option is used to set the maximum columns to be displayed. If we want to display the all columns , we have to specify as None in n parameter.
  • pd.set_option(‘display.width’, n)
    • This option is used to set the width of the dataframe in n parameter.
  • pd.set_option(‘display.colheader_justify’, ‘right/center/left’)
    • This option is used to display the column header the dataframe in the specified position.
  • pd.set_option(‘display.precision’, n)
    • This option is used to set the precision for the column in the dataframe

Let’s see the example code

#display all rows
pd.set_option('display.max_rows', None)

#display all columns
pd.set_option('display.max_columns', None)

#set width as 100
pd.set_option('display.width', 100)

#set column header in left
pd.set_option('display.colheader_justify', 'left')

#set precision as 5
pd.set_option('display.precision', 5)

#display dataframe
print(df)

Output:

   id name       age subjects 
0  58    sravan  22       java
1  59  jyothika  21        php
2  60   preethi  22        sql
3  61   srinadh  23   r/python

Here , we are going to display the dataframe in table format with width as 100 and precision as 5 to display all rows and columns. Also all column headers are left alligned.

Using option_context() method

This method will also takes same parameters as set_option() method while setting all the parameters in a single call.

Let’s see the example

# using option_context()
# to display all rows and columns
# with table width as 100 with column precision as 5
# with columns headers of left align
with pd.option_context('display.max_rows', None,
                       'display.max_columns', None,
                       'display.width', 100,
                       'display.precision', 5,
                       'display.colheader_justify', 'left'):
    # Display the Dataframe
    print(df)

Output:

   id name       age subjects 
0  58    sravan  22       java
1  59  jyothika  21        php
2  60   preethi  22        sql
3  61   srinadh  23   r/python

Here , we displayed the dataframe in table format with width as 100 and precision as 5 to display all rows and columns. Also column headers are left aligned.

Print Dataframe with or without Index

In Pandas, the Dataframe provides a member function to_strint(). It returns a string i.e. in console-friendly tabular format. We are going to use that to print a Dataframe with & without index. For example,

# Display the dataframe and ignore index
print(df.to_string(index=False))

# Display the dataframe with index
print(df.to_string(index=True))

Output:

 id      name  age  subjects
 58    sravan   22      java
 59  jyothika   21       php
 60   preethi   22       sql
 61   srinadh   23  r/python


   id      name  age  subjects
0  58    sravan   22      java
1  59  jyothika   21       php
2  60   preethi   22       sql
3  61   srinadh   23  r/python

Pretty Print Pandas Dataframe to HTML

We are going to convert the dataframe into HTML format and print the dataframe using to_html() function.
Syntax is as follows:

df.to_html('name.html')

where, df is the input dataframe and name is the name of the HTML converted.

Example Code:

#print in html
df.to_html('data.html')

It created a html file i.e. data.html. In the html file Dataframe contents are saved in table format using <table>, <tr> and <td> tags. When you will open the html file in browser, then it will be like this,

Dataframe to html

Pretty Print Dataframe in Markdown Format

We will print dataframe in markdown format. Markdown is a lightweight markup language which will create the formatted text from the plain-text editor.

Syntax:

df.to_markdown()

It Returns the Dataframe contents in Markdown-friendly format string.

It requires the tabulate package. You can install it using following command

pip install tabulate

Example: Print the dataframe in markdown format.

# print dataframe in Markdown format
print(df.to_markdown())

Output:

|    |   id | name     |   age | subjects   |
|---:|-----:|:---------|------:|:-----------|
|  0 |   58 | sravan   |    22 | java       |
|  1 |   59 | jyothika |    21 | php        |
|  2 |   60 | preethi  |    22 | sql        |
|  3 |   61 | srinadh  |    23 | r/python   |

Pretty Print Dataframe using Tabulate Package

We can print dataframe in different formats using tabulate moduleBefore that we have to install this package. The command is

pip install tabulate

Syntax:

tabulate(df, headers='keys', tablefmt)

where, df is the input dataframe and headers refers to the columns. Lets see the different formats.

Pretty Print Dataframe in psql format

This format will prints the dataframe in plsql format.

Syntax:

tabulate(df, headers='keys', tableformat='psql')

Example:

#import tabulate module
from tabulate import tabulate

#print dataframe in psql format by specifying headers
print(tabulate(df, headers='keys', tablefmt='psql'))

Output:

+----+------+----------+-------+------------+
|    |   id | name     |   age | subjects   |
|----+------+----------+-------+------------|
|  0 |   58 | sravan   |    22 | java       |
|  1 |   59 | jyothika |    21 | php        |
|  2 |   60 | preethi  |    22 | sql        |
|  3 |   61 | srinadh  |    23 | r/python   |
+----+------+----------+-------+------------+

Pretty Print Dataframe in fancy grid format

This format will prints the dataframe in grid format.

Syntax:

tabulate(df, headers='keys', tableformat='fancy_grid')

Example:

#import tabulate module
from tabulate import tabulate

#display in fancy grid format
print(tabulate(df, headers='keys', tablefmt='fancy_grid'))

Output:

╒════╤══════╤══════════╤═══════╤════════════╕
│    │   id │ name     │   age │ subjects   │
╞════╪══════╪══════════╪═══════╪════════════╡
│  0 │   58 │ sravan   │    22 │ java       │
├────┼──────┼──────────┼───────┼────────────┤
│  1 │   59 │ jyothika │    21 │ php        │
├────┼──────┼──────────┼───────┼────────────┤
│  2 │   60 │ preethi  │    22 │ sql        │
├────┼──────┼──────────┼───────┼────────────┤
│  3 │   61 │ srinadh  │    23 │ r/python   │
╘════╧══════╧══════════╧═══════╧════════════╛

Pretty Print Dataframe in plain-text format

This format will prints the dataframe in text format.

Syntax:

tabulate(df, headers='keys', tableformat='plain')

Example:

#import tabulate module
from tabulate import tabulate

#display in plain text format
print(tabulate(df, headers='keys', tablefmt='plain'))

Output:

      id  name        age  subjects
 0    58  sravan       22  java
 1    59  jyothika     21  php
 2    60  preethi      22  sql
 3    61  srinadh      23  r/python

Pretty Print Dataframe in RST format

This format will prints the dataframe in restructured text format.

Syntax:

tabulate(df, headers='keys', tableformat='rst')

Example:

#import tabulate module
from tabulate import tabulate

#display in restructured text format
print(tabulate(df, headers='keys', tablefmt='rst'))

Output:

====  ====  ========  =====  ==========
  ..    id  name        age  subjects
====  ====  ========  =====  ==========
   0    58  sravan       22  java
   1    59  jyothika     21  php
   2    60  preethi      22  sql
   3    61  srinadh      23  r/python
====  ====  ========  =====  ==========

Pretty Print Dataframe in HTML format

This format will prints the dataframe in HTML format.

Syntax:

tabulate(df, headers='keys', tableformat='html')

Example:

#import tabulate module
from tabulate import tabulate

#display in html format
print(tabulate(df, headers='keys', tablefmt='html'))

Output:

<table><thead>
<tr><th style="text-align: right;">  </th><th style="text-align: right;">  id</th><th>name    </th><th style="text-align: right;">  age</th><th>subjects  </th></tr>
</thead>
<tbody>
<tr><td style="text-align: right;"> 0</td><td style="text-align: right;">  58</td><td>sravan  </td><td style="text-align: right;">   22</td><td>java      </td></tr>
<tr><td style="text-align: right;"> 1</td><td style="text-align: right;">  59</td><td>jyothika</td><td style="text-align: right;">   21</td><td>php       </td></tr>
<tr><td style="text-align: right;"> 2</td><td style="text-align: right;">  60</td><td>preethi </td><td style="text-align: right;">   22</td><td>sql       </td></tr>
<tr><td style="text-align: right;"> 3</td><td style="text-align: right;">  61</td><td>srinadh </td><td style="text-align: right;">   23</td><td>r/python  </td></tr>
</tbody>
</table>

Pretty Print Dataframe in github format

This format will prints the dataframe in github format.

Syntax:

tabulate(df, headers='keys', tableformat='github')

Example:

#import tabulate module
from tabulate import tabulate

#display in github format
print(tabulate(df, headers='keys', tablefmt='github'))

Output:

|    |   id | name     |   age | subjects   |
|----|------|----------|-------|------------|
|  0 |   58 | sravan   |    22 | java       |
|  1 |   59 | jyothika |    21 | php        |
|  2 |   60 | preethi  |    22 | sql        |
|  3 |   61 | srinadh  |    23 | r/python   |

Pretty Print Dataframe in pretty format

This format will prints the dataframe in pretty format.

Syntax:

tabulate(df, headers='keys', tableformat='pretty')

Example:

#import tabulate module
from tabulate import tabulate

#display in pretty format
print(tabulate(df, headers='keys', tablefmt='pretty'))

Output:

+---+----+----------+-----+----------+
|   | id |   name   | age | subjects |
+---+----+----------+-----+----------+
| 0 | 58 |  sravan  | 22  |   java   |
| 1 | 59 | jyothika | 21  |   php    |
| 2 | 60 | preethi  | 22  |   sql    |
| 3 | 61 | srinadh  | 23  | r/python |
+---+----+----------+-----+----------+

Pretty Print Dataframe in tsv format

tsv stands for tab separated value.

This format will prints the dataframe in tsv format.

Syntax:

tabulate(df, headers='keys', tableformat='tsv')

Example:

#import tabulate module
from tabulate import tabulate

#display in tsv format
print(tabulate(df, headers='keys', tablefmt='tsv'))

Output:

        id    name          age   subjects
 0      58    sravan         22   java
 1      59    jyothika       21   php
 2      60    preethi        22   sql
 3      61    srinadh        23   r/python
 

Summary

In this article, we discussed how to pretty print pandas dataframe with 4 methods and in different formats.

Advertisements

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top