How to make table in python

How to Easily Create Tables in Python

How to use the tabulate function to create nicely-formatted tables in Python

Being able to quickly organize our data into a more readable format, such as when data wrangling, can be extremely helpful in order to analyze the data and plan the next steps. Python offers the ability to easily turn certain tabular data types into nicely formatted plain-text tables, and that’s with the tabulate function.

install tabulate

We first install the tabulate library using pip install in the command line:

import tabulate function

We then import the tabulate function from the tabulate library in our code:

from tabulate import tabulate

And now we are ready to use the tabulate function!

Читайте также:  Filter array of objects javascript

tabular data types supported by tabulate

The tabulate function can transform any of the following into an easy to read plain-text table: (from the tabulate documentation)

  • list of lists or another iterable of iterables
  • list or another iterable of dicts (keys as columns)
  • dict of iterables (keys as columns)
  • two-dimensional NumPy array
  • NumPy record arrays (names as columns)
  • pandas.DataFrame

list of lists

For example, if we have the following list of lists:

table = [['First Name', 'Last Name', 'Age'], 
['John', 'Smith', 39],
['Mary', 'Jane', 25],
['Jennifer', 'Doe', 28]]

We can turn it into into a much more readable plain-text table using the tabulate function:

Since the first list in the list of lists contains the names of columns as its elements, we can set it as the column or header names by passing ‘firstrow’ as the argument for the headers parameter:

print(tabulate(table, headers='firstrow'))

Источник

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

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

Источник

How to make a table in Python

In this article, you are going to learn about how to make a table in the Python programming language.

Python is a high-level interpreted programming language that provides a rich amount of library support to accomplish a certain task. Creating tables is not out of them. Python provides useful modules for creating tables. We can use the tabulate module or PrettyTable module for creating a table in Python and in this article, we are going to explore these two module and see how we can create a table in python by using them. Let’s start with the tabulate module.

Creating Table By Using The Tabulate Module

We can easily create a table in the python programming language by using this tabulate module. But at first, we need to install it. The process is very easy and all we need to do is to give the below command in our terminal.

# Commmand for installing tabulate module pip install tabulate

This command will install this module in our python program and now we are ready to use this module. Let’s see the simple example of creating a table in python.

from tabulate import tabulate student_data = [ ["Alex", "20"], ["Deven", "23"], ["John", "21"], ["Rohit", "25"] ] heading = ["Name", "Age"] print(tabulate(student_data, headers=heading)) # Output: # Name Age # ------ ----- # Alex 20 # Deven 23 # John 21 # Rohit 25

Here, you can see how easily we have created a table by using the tabular module. This is the simplest example of creating a table. We can also design this table such as fancy_grid, grid, pipe, pretty or simple Let me show you by using one of them. Let’s say we want to use the pretty to design our table. See the below code:

from tabulate import tabulate student_data = [ ["Alex", "20"], ["Deven", "23"], ["John", "21"], ["Rohit", "25"] ] heading = ["Name", "Age"] print(tabulate(student_data, headers=heading, tablefmt="pretty")) # Output: # +-------+-----+ # | Name | Age | # +-------+-----+ # | Alex | 20 | # | Deven | 23 | # | John | 21 | # | Rohit | 25 | # +-------+-----+

Here, you can see that all we have done is just pass a new argument as tablefmt=»pretty» and it has designed our table nicely. You may also try the other options and the process of doing so is as same as this.

Creating Table By Using The PrettyTable Module

We can also create a table in python by using the prettytable module and as before, we need to install it first before using it. See the below command example for installing it:

# Commmand for installing prettytable module pip install prettytable

After installing this module, we are ready to use it. The process of using it is a bit different from the tabulate module. Let’s take the previous example and try to implement it with the prettytable module in the below section:

from prettytable import PrettyTable student_table = PrettyTable(["Name", "Age"]) student_table.add_row(["Alex" , "20"]) student_table.add_row(["Deven", "23"]) student_table.add_row(["John" , "21"]) student_table.add_row(["Rohit", "25"]) print(student_table) # Output: # +-------+-----+ # | Name | Age | # +-------+-----+ # | Alex | 20 | # | Deven | 23 | # | John | 21 | # | Rohit | 25 | # +-------+-----+

This is all about creating table in the python programming language and you may follow any one of these modules for creating your own table in Python.

Источник

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