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

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

  • автор:

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

Printing Lists as Tabular Data

I am quite new to Python and I am now struggling with formatting my data nicely for printed output.

I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so:

Note that the heading names are not necessarily the same lengths. The data entries are all integers, though.

Now, I want to represent this in a table format, something like this:

I have a hunch that there must be a data structure for this, but I cannot find it. I have tried using a dictionary and formatting the printing, I have tried for-loops with indentation and I have tried printing as strings.

I am sure there must be a very simple way to do this, but I am probably missing it due to lack of experience.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

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

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

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

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

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

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

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

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

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

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

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

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

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

Примечание: в F-string в фигурных скобках <> помещены «заменяющие поля». Двоеточие : указывает на поле format_spec , что означает нестандартный формат замены. Для него существует Мини-язык спецификации формата.

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

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

Python Print Table

By Priya PedamkarPriya Pedamkar

python print table

Introduction to Python Print Table

Python is quite a powerful language when it comes to 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?

There are several ways that 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
  • texttable
  • beautifultable
  • PrettyTable

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 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 in order 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 along with the print statement to print tables in a readable format.

Conclusion

Reading data in a tabular format is much easier as compared to 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 –

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

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