Как вывести таблицу в python
Перейти к содержимому

Как вывести таблицу в python

  • автор:

Python Print Table

Priya Pedamkar

Python is quite a powerful language regarding its data science capabilities. Moreover, the Printing tables within Python are sometimes challenging, as the trivial options provide you with the output in an unreadable format. We got you covered. There are multiple options to transform and print tables into many pretty and more readable formats. If you are working on Python in a Unix / Linux environment, then readability can be a huge issue from the user’s perspective.

How to Print Table in Python?

Several ways can be utilized to print tables in Python, namely:

  • Using format() function to print dict and lists
  • Using tabulate() function to print dict and lists
  • text table
  • beautiful table
  • Pretty Table

Reading data in a tabular format is much easier as compared to an unstructured format, as given below:

  • Pos, Lang, Percent, Change
  • 1, Python, 33.2, UP
  • 2, Java, 23.54, DOWN
  • 3, Ruby, 17.22, UP
  • 5, Groovy, 9.22, DOWN
  • 6, C, 1.55, UP
  • 10, Lua, 10.55, DOWN

Tabular Format

Pos Lang Percent Change
1 Python 33.2 UP
2 Java 23.54 DOWN
3 Ruby 17.22 UP
5 Groovy 9.22 DOWN
6 C 1.55 UP
10 Lua 10.55 DOWN

How can we Print Tables in Python?

We tend to use information from a dictionary or a list quite frequently. One way of printing the same can be:

1. Unformatted Fashion

Let us take an example to understand this in detail

Code:

Output:

Python Print Table - 1

The above example’s output is quite unreadable; let’s take another example of how we can print readable tables in Python.

2. Formatted Fashion

Code:

Output:

Python Print Table - 2

  • This gives us a better readability option using the format function in a print command.
  • What if we want to print the data from a list in a tabular format in Python? How can this be done?
3. By utilizing the Format Function

Code:

Output:

Python Print Table - 3

4. By utilizing the Tabulate Function

Let’s have another example to understand the same in quite some detail.

Code:

Output:

Tabulate Function

The best part is that you do not need to format each print statement whenever you add a new item to the dictionary or the List. There are several other ways as well that can be utilized to print tables in Python, namely:

  • texttable
  • beautifultable
  • PrettyTable
  • Otherwise, Pandas is another pretty solution if you are trying to print your data in the most optimized format.
5. Print the table using pandas in detail

Pandas is a Python library that provides data handling, manipulation, and diverse capabilities to manage, alter and create meaningful metrics from your dataset. Let’s take the below example to understand the print table option with pandas in detail.

Output:

pandas in detail

How does it work?

  • We imported the panda’s library using the import statement
  • >> Import pandas
  • Thereafter declared a list of lists and assigned it to the variable named “data.”
  • in the very next step, we declared the headers
  • >> headers=[“Pos”, “Team”, “Win”, “Lose”]

How can we print this List in a Formatted Readable Structure?

  • Pandas have the power of data frames, which can handle, modify, update, and enhance your data in a tabular format.
  • We have utilized the data frame module of the pandas’ library and the print statement to print tables in a readable format.

Conclusion

Reading data in a tabular format is much easier than in an unstructured format. Utilizing the capability of Python print statements with numerous functions can help you attain better readability for the same.

Recommended Articles

This is a guide to Python Print Table. Here we discuss the introduction to Python Print Table and how to print tables with different examples. You can also go through our other related articles to learn more –

�� Making tables in Python

Let’s see some tricks to drawing tables in your terminal!

Mina Pêcheux

CodeX

Whenever you want to display data, tables are one of the go-to solutions. They may not be very elegant, they may not have flashy colours like pie charts and histograms, but they are an effective way to show a massive amount of data in a condensed and objective way.

This idea of showing your data in an unobstructed and “fair” manner is crucial to data analysis. In this day and age of data overflood where we are constantly bombarded with dozens of pieces of info on every topic, the issue is not so much about gathering data than about shaping it properly.

And, tables, for all their aesthetic flaws, are a good technique to presenting your data without too much fluff around it. You don’t have a fancy legend to play around with to confuse your viewers, or some strange axis scales to hide the bad sales with…

So, today, let’s see how to print basic tables for some arbitrary data in the shell using Python! 🙂

Preparing our data

Ok, before we dive into actually displaying anything, it is important to decide what we expect the data to look like. In a real data pipeline, you always need to define the input and output format you want for each step of the process, and it is the job of the previous steps (or, in our case, the user writing up the fake data) to obey these rules.

Here, I’m going to assume that my table items are a list of Python dicts with common keys, like this:

You see that each item has the same three keys ( name , age and job ), which will correspond to our columns in the table. By the end of the tutorial, our little table utility will be able to take this data in as-is and print something like this in the shell:

Print Table on console in Python

Displaying your data on the console in the form of a formatted table can be useful in many cases. It makes it easy to look at the data. In this post, I will discuss different modules that can help you accomplish the job.

PrettyTable

Installation

Documentation

Usage

Import PrettyTable from the prettytable module and create a new table. Then, you can use the add_row function to add a new row to the table.

The fields are marked as Field 1, Field 2, and so on. If you want custom field names, you can use field_names to achieve that.

Sort the rows of Table

Pretty Table also provides the feature to sort the data with respect to a particular field. For example, if we wanted to sort people by their age in the above table, we could use the sortby option.

The data is sorted in ascending order. If it is required to sort the data in descending order, the reversesort option can be used.

Delete the rows of Table

The function del_row can be used to delete a row from the table. It takes the row number as the parameter.

Clear All Data

All the data can be cleared by using the function clear_rows.

TextTable

Installation

Documentation

Usage

When I started reading the Python Package Index Page for this module, I immediately realized that this one is more advanced than the others.

Let’s start with a very simple usage example. Print a simple table.

Add all Rows at once

Now let’s talk about the advanced features which let you better format your data.

Set Alignment of the Columns

You can set the alignment of the columns using the set_cols_align function. It takes a list as a parameter in which ‘l’ means left align and ‘r’ means right align.

Set the data type

We can also set the data types of the columns using the set_cols_dtype function. Please note that the data type must be set before setting the data.

Here ‘i’ means integer, ‘t’ means text, and so on. The output of the code is:

Here is a list of different data types that you can set.

a automatic (try to use the most appropriate datatype)
t treat as text
f treat as float in decimal format
e treat as float in exponential format
i treat as int
Vertical Alignment of Columns

You can also set the vertical alignment of the columns in case any row contains more than one line of info. You will set ‘t’ for top, ‘m’ for middle and ‘b’ for bottom.

Set decoration type

You can use the set_deco function to set the decoration of the table. The following options are available.

Texttable.BORDER Border around the table
Texttable.HEADER Horizontal line below the header
Texttable.HLINES Horizontal lines between rows
Texttable.VLINES Vertical lines between columns

All of these options are enabled by default. Let’s see how to use them by an example

Как напечатать таблицу с помощью f-string

Разберём, как напечатать красивую таблицу с одинаковой шириной колонок, с разной шириной колонок, с шапкой из двух строк. Создадим функцию с параметром максимальной ширины таблицы и функцию для записи таблицы в текстовый файл.

В этой статье мы разберём как напечатать красивые таблицы:

  • с одинаковой шириной колонок;
  • с разной шириной колонок;
  • с шапкой из двух строк.

А также создадим функции:

  • с параметром максимальной ширины таблицы;
  • для записи таблицы в текстовый файл.

«F-строки» были введены ещё в версии Python 3.6, и все уже давно, наверно, их используют в своём коде. Для тех, кто хочет освежить память, и ещё раз перечитать документацию — PEP 498 – Literal String Interpolation. Мы же будем использовать «f-строки» для вывода данных в табличном виде. Для примера возьмём данные об автомобилях с одного из онлайн-рынков такой структуры:

Таблица с одинаковой шириной колонок

Для того, чтоб данные в колонках таблицы выровнять по центру, левому или правому краю, нужно рассчитать ширину колонок и определить отступ. Давайте сделаем ширину колонок одинаковой по максимальной строке столбца и отступом в один символ.

Функция с параметром максимальной ширины таблицы

Давайте соберём наш код в функцию, но добавим ещё один параметр — максимальную ширину таблицы. И если ширина таблицы будет больше максимальной, заданной по умалчиванию — выведем сообщение. А также сделаем выравнивание текста в строках шапки таблицы по центру, в теле таблицы — по правому краю. Для этого надо всего лишь перед значением ширины строки вставить символ «^» — выравнивание по центру, «>» — выравнивание по правому краю, «

Давайте ещё изменим вывод нашей таблицы. Колонки «Цена $» и «Пробег км» выведем с , , как разделитель тысяч.

Здесь, в 52 строке кода, в f',> ‘ перед закрывающей фигурной скобкой вставлена запятая, как разделитель тысяч (кроме «,» можно ещё использовать «_»), ну а дальше форматирование сделает всё само:

Но это ещё не все возможности «спецификации формата».

Функция для записи таблицы в текстовый файл

Часто приходится не только печатать таблицу, но и сохранять её в текстовом файле. Имея готовую функцию для печати, нетрудно переделать её для записи.

Подпишитесь на интересующие вас теги, чтобы следить за новыми постами и быть в курсе событий.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *