Generate table in python

3 Simple Ways to Quick Generate Text-based Tables in Python

Simple but helpful libraries to create text-based tables

Introduction

These days, I often spend some time reading about new Python packages in the mornings. Surprisingly, there have been so many simple yet useful libraries that I wish I had known about them sooner.

I tried to summarize them into different topics, and in this article today, I’d like to discuss one of these topics with you: “How to create tables in Python quickly?”.

Now, let’s see what we have here.

PrettyTable

PrettyTable is a Python package that allows you to create basic ASCII tables. Different table patterns, such as text alignment or data order, can be customized easily with simple codes. For more details, let’s look at a few examples below.

But first, installing this package by:

!pip install prettytable 
from prettytable import PrettyTable as pt

Creating table

We can apply add_row or add_column methods to generate desired tables. The table output is as follows:

tb = pt()#Add headers
tb.field_names = ["ID","Name", "Major","Grade"]
#Add rows
tb.add_row([1,"Chi", "Statistics",3.5])
tb.add_row([2,"John","Business Administration"],3.6)
tb.add_row([3,"Lily","Satistics"],3.7)
print(tb)
tb1 = pt()#Add headers
column_names = ["ID","Name", "Major"]
#Add columns
tb1.add_column(column_names[0],[1,2,3])
tb1.add_column(column_names[1],["Chi","John","Lily"])
tb1.add_column(column_names[2],["Statistics","Business Administration","Statistics"])
tb1.add_column(column_names[3],[3.5,3.6,3.7])
print(tb1)

Naming the table

We can name the table by putting the title to it with get_string(title = “table name»)

Источник

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
Читайте также:  Значок смены языка html

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

Источник

Easiest way to turn a list into an HTML table in python?

Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don’t have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?

7 Answers 7

from tabulate import tabulate table = [['one','two','three'],['four','five','six'],['seven','eight','nine']] print(tabulate(table, tablefmt='html')) 

Which produces the following output.

 
one two three
four five six
seveneightnine

I would decompose your problem into two parts:

  • given a «flat list», produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a «row major» order (your first and third example) or «column major» (your second example);
  • given a list of sublists with string items, produce an HTML table out of it.

I think the two tasks are really very distinct and there’s nothing to gain (and much to lose) in mushing them up, so I would be astonished if any well-designed library did such mushing.

For point 1, row-major is easy:

def row_major(alist, sublen): return [alist[i:i+sublen] for i in range(0, len(alist), sublen)] 

and column-major not that bad:

def col_major(alist, sublen): numrows = (len(alist)+sublen-1) // sublen return [alist[i::sublen] for i in range(numrows)] 
L = ['one','two','three','four','five','six','seven','eight','nine'] for r in row_major(L, 3): print r print for r in col_major(L, 3): print r for r in row_major(L, 4): print r 

produces your three desired results (one list per row, not in HTML form yet;-).

The second half of the problem — produce an HTML table from a list of lists of strings:

def html_table(lol): print '' for sublist in lol: print ' ' print '
' print ' '.join(sublist) print '
'

If you want to get it as a single string rather than print it out, change each print into yield and use ‘\n’.join(html_table(lol)) .

Now you have two simple, useful, usable and reusable building blocks — having them separate will come in handy whenever you want to present your data as anything BUT an HTML table, and also whenever the list-of-lists to present as an HTML table comes from any other way of building it. Putting them together is easy to do in your application code, but of course it’s also easy to do a simple «glue routine», e.g., assuming the yield -based version of html_table and that a single string result is desired:

def list_to_html_table(alist, sublength, column_major=False): if column_major: lol = col_major(alist, sublength) else: lol = row_major(alist, sublength) return ''.join(html_table(lol)) 

Isn’t this building-blocks approach really nicer and more pleasant, as well as more productive, than programming in terms of big blobs of mushed-up glue. -)

Источник

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