Table structure in python

How to Create Table in Python

In this document, you will learn how to create tables in Python, how to format them, and how parsing is useful. Python provides tabulate library to create tables and format them.

To install the tabulate library execute the below command on your system:

What is Tabulate Module?

This module helps in pretty-print tabular data in Python; a library that helps in providing better command-line utility. The main usages of the module are:

  • printing miniature sized tables without hassle or formatting tools. It requires only one function call, nor another formatting requirement. This module can easily understand how to frame the table.
  • composing tabular data for lightweight plain-text markup: numerous output forms appropriate for additional editing or transformation
  • readable presentation of diverse textual and numeric data: configurable number formatting, smart column alignment, alignment by a decimal point
Читайте также:  Javascript alert box example-1

It leverages a method called the tabulate() that takes a list containing n nested lists to create n rows table.

from tabulate import tabulate table = [[‘Aman’, 23],[‘Neha’, 25],[‘Lata’, 27]] print(tabulate(table))

Explanation:

Here we have used the module Tabulate that takes a list of lists (also known as a nested list) and stored it under the object name table. Then we use the tabulate() method where we passed the table object (nested list). This will automatically arrange the format in a tabular fashion.

Table Headers

To get headers or column headings you can use the second argument in tabulate() method as headers. For example,

from tabulate import tabulate table = [[‘Aman’, 23], [‘Neha’, 25], [‘Lata’, 27]] print(tabulate(table), headers = [‘Name’, ‘Age’])

Explanation:

Here we have used the module Tabulate that takes a list of lists (also known as a nested list) and stored it under the object name table. Then we use the tabulate() method where we passed the ‘table’ object (nested list). This time we take another parameter headers that takes two string values ‘Name’ and ‘Age’ that will be the title of the columns. This will automatically arrange the format in a tabular fashion.

In the list of lists, you can assign the first list for column headers containing all column headings, and assign headers’ value as “firstrow”.

from tabulate import tabulate table = [['Name', 'Age'], ['Aman', 23], ['Neha', 25], ['Lata', 27]] print(tabulate(table, headers = "firstrow" ))

You can also pass a dictionary to tabulate() method where keys will be the column headings and assign headers’ value as “keys”.

from tabulate import tabulate table = [['Name', 'Age'], ['Aman', 23], ['Neha', 25], ['Lata', 27]] print(tabulate(, headers = 'keys'))

Row Index

You can display the index column containing indexes for all rows in the table.

tabulate(<"Name":['Aman', 'Lata', 'Neha'], 'Age': [23, 25, 28]>, headers = 'keys', showindex = True)

To hide the index column you can use showindex as ‘False’ or showindex as ‘never’ .

tabulate(<"Name":['Aman', 'Lata', 'Neha'], 'Age' : [23,25,28]>, headers = 'keys', showindex = "never")
tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers = 'keys', showindex = False)

To have a custom index column, pass an iterable as the value of showindex argument.

li=[2,4,6] tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers = 'keys', showindex = li)

Number formatting

The tabulate() method allows you to display the specific count of numbers after a decimal point in a decimal number using floatfmt argument.

Example: Adding a new column Height in the above example:

table=tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28],'Height':[153.4567,151.2362,180.2564]>, headers='keys')

Formatting the height values up to two digits:

tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28], 'Height':[153.4567,151.2362,180.2564]>, headers='keys', floatfmt='.2f')

Table format

You can format the table in multiple ways using tablefmt argument. Following are a few of them:

plain: It formats the table in a plain simple way without any outer lines:

tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers='keys', tablefmt="plain")

simple: It is the default formatting in tabulate() method that displays the table with one horizontal line below the headers:

tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers='keys', tablefmt="simple")

html: It displays the table in html code format:

tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers='keys', tablefmt="html")

jira: Displays the table in Atlassian Jira markup language format:

tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers = 'keys', tablefmt = "jira")

Psql: It displays the table in Postgres SQL form.

For example: tabulate(<"Name":['Aman', 'Lata', 'Neha'],'Age':[23,25,28]>, headers='keys', tablefmt="psql")

Github: It displays the table in GitHub mardown form.

For example: tabulate(<"Name":['Aman', 'Lata', 'Neha'], 'Age':[23,25,28]>, headers = 'keys', tablefmt = "github")

Pretty: Displays table in the form followed by PrettyTables library

For example: tabulate(<"Name":['Aman', 'Lata', 'Neha'], 'Age':[23,25,28]>, headers='keys', tablefmt = "pretty")

PrettyTable Module:

PrettyTable is another Python library that helps in creating simple ASCII tables. It got inspired by the ASCII tables generated and implemented in the PostgreSQL shell psql. This library allows controlling many aspects of a table, such as the the alignment of text, width of the column padding, or the table border. Also it allows sorting data.

Creating a Table using Python:

Creating a table in Python is very easy using the PrettyPrint library. Simply import the module and use its add_row() method to add multiple rows or create a table row-wise.

from prettytable import PrettyTable myTab = PrettyTable(["Agent Name", "Rank", "Division", "Attack Quality"]) # Add rows myTab.add_row(["John", "Major", "B", "90.00 %"]) myTab.add_row(["Kenny", "Captain", "C", "73.50 %"]) myTab.add_row(["Karlos", "Secret", "A", "80.50 %"]) myTab.add_row(["Ray", "Spy", "D", "92.00 %"]) myTab.add_row(["Gaurav", "Technical Head", "A", "89.00 %"]) myTab.add_row(["Bill", "X", "Major", "78.50 %"]) myTab.add_row(["Mark", "X", "Spy", "96.00 %"]) myTab.add_row(["Steve", "X", "Captain", "75.00 %"]) print(myTab)

Example to create a table column-wise:

from prettytable import PrettyTable columns = ["Employee Name", "Class", "Division", "Salary"] myTab = PrettyTable() # Add Columns myTab.add_column(columns[0], ["Karl", "Kenny", "Ray", "Steve", "Gaurav", "David", "Harry"]) myTab.add_column(columns[1], ["A", "A", "A", "A", "A", "A", "A"]) myTab.add_column(columns[2], ["1st", "1st", "1st", "2nd", "1st", "2nd", "1st"]) myTab.add_column(columns[3], ["39K", "43K", "1.2L %", "2.3L", "56K", "73K", "33K"]) print(myTab)

Table plays a significant role in software development where the developer wants to create a formatted output. A lot of CLI-based software requires such formatting. Formatting through tabular form also helps in giving a crisp idea of the data so that the users can easily understand what the data wants to convey. Both these modules work well for representing data in tabular format. Web development using Python also requires these modules.

  • Learn Python Programming
  • Python Training Tutorials for Beginners
  • pip is not recognized
  • Python Min()
  • Python lowercase
  • Python Uppercase
  • Python map()
  • Polymorphism in Python
  • Python Pass Statement
  • Python String Contains
  • Python eval
  • Python Split()
  • Ord Function in Python
  • Only Size-1 Arrays Can be Converted to Python Scalars
  • Area of Circle in Python
  • Python Combine Lists
  • Python slice() function
  • Python Sort Dictionary by Key or Value
  • Compare Two Lists in Python
  • Python KeyError

Источник

Python tabulate module: How to Easily Create Tables in Python?

tables in Python tabulate module

In this tutorial, you are going to explore how to create tables in Python, a necessary skill in the realm of data science, with the help of the tabulate function. We’ll also learned about the different properties involved with creating tables.

Python tabulate makes creating and formatting tables easy and efficient. Start by importing the module. You can then create a table by storing your data in a nested list and passing it to the tabulate function. To enhance the look of your table, use the tablefmt attribute and set it to grid for a bordered table, or fancy_grid for a more sophisticated border. If you need the HTML code, set tablefmt to ‘html’.

Step-by-Step Guide to Creating Tables with Python’s Tabulate Module

Without any further ado, let’s get right into the steps to create tables in Python with the use of the tabulate module.

Step 1: Setting the Stage – Importing Tabulate

Firstly, we need to import the tabulate function from the tabulate library, a Python package widely used in data science and machine learning projects. In case this results in an error make sure you have the tabulate library installed by executing the pip install command on the command prompt.

from tabulate import tabulate

Now let’s create our very first table with the help of the tabulate function. In data science, it’s often necessary to organize large quantities of data in a structured, readable format – that’s where Python tabulate comes handy.

Step 2: Building the Basics – Creating Simple Tables

The data of the table is stored in the form of nested lists as shown in the code mentioned below.

all_data = [["Roll Number","Student name","Marks"], [1,"Sasha",34], [2,"Richard",36], [3,"Judy",20], [4,"Lori",39], [5,"Maggie",40]]

To tabulate the data, we just pass the data to the tabulate function. We can also make the first nested list as the head of the table by using an attribute known as headers .

table1 = tabulate(all_data) table2 = tabulate(all_data,headers='firstrow') print(table1) print(table2)

The results of both the tables are shown below.

----------- ------------ ----- Roll Number Student name Marks 1 Sasha 34 2 Richard 36 3 Judy 20 4 Lori 39 5 Maggie 40 ----------- ------------ -----
Roll Number Student name Marks ------------- -------------- ------- 1 Sasha 34 2 Richard 36 3 Judy 20 4 Lori 39 5 Maggie 40

The presentation of data is just as important as the analysis. By neatly aligning columns and adding borders, we ensure our tables are not only readable but also pleasing to the eye.

Step 3: Amplifying the Aesthetics – Formatting Your Python Table

To make tables in Python look better, we can add borders for the table to make it look more tabular instead of textual data. The borders can be added with the help of the tablefmt attribute and set its value to grid .

print(tabulate(all_data,headers='firstrow',tablefmt='grid'))
+---------------+----------------+---------+ | Roll Number | Student name | Marks | +===============+================+=========+ | 1 | Sasha | 34 | +---------------+----------------+---------+ | 2 | Richard | 36 | +---------------+----------------+---------+ | 3 | Judy | 20 | +---------------+----------------+---------+ | 4 | Lori | 39 | +---------------+----------------+---------+ | 5 | Maggie | 40 | +---------------+----------------+---------+

To make it look better, we can use fancy_grid instead of a simple grid. In Python’s tabulate, ‘fancy_grid’ offers a nicely formatted and visually appealing output, suitable for presenting complex data in a clear, digestible manner.

print(tabulate(all_data,headers='firstrow',tablefmt='fancy_grid'))
╒═══════════════╤════════════════╤═════════╕ │ Roll Number │ Student name │ Marks │ ╞═══════════════╪════════════════╪═════════╡ │ 1 │ Sasha │ 34 │ ├───────────────┼────────────────┼─────────┤ │ 2 │ Richard │ 36 │ ├───────────────┼────────────────┼─────────┤ │ 3 │ Judy │ 20 │ ├───────────────┼────────────────┼─────────┤ │ 4 │ Lori │ 39 │ ├───────────────┼────────────────┼─────────┤ │ 5 │ Maggie │ 40 │ ╘═══════════════╧════════════════╧═════════╛

Step 4: The Web Twist – Extracting HTML Code from Tabulate

To extract the HTML code of the table, we need to set the tablefmt attribute to html . The same is displayed below.

print(tabulate(all_data,headers='firstrow',tablefmt='html'))
 
Roll NumberStudent name Marks
1Sasha 34
2Richard 36
3Judy 20
4Lori 39
5Maggie 40

Getting the HTML code from tabulate provides a gateway to integrate your data with web applications, further extending its use in data science.

Wrapping Up: Power of Tabulate in Python

In this tutorial, we created our own tabular data using the tabulate function and also learned about some properties of the tables. Python libraries like tabulate and prettytable not only make data manipulation easy but also enhance the readability of your output. Whether you’re working on machine learning projects or diving deep into data analysis, mastering these tools can help elevate your work.

Источник

Оцените статью