Prettytable es una biblioteca de Python que se utiliza para imprimir tablas ASCII en una forma atractiva y para leer datos de CSV, HTML o cursor de base de datos y generar datos en ASCII o HTML. Podemos controlar muchos aspectos de una tabla, como el ancho del relleno de la columna, la alineación del texto o el borde de la tabla.
Instalación
Para poder usar la biblioteca prettytable primero, debemos
instalarla usando el comando de la herramienta pip:
pip install prettytable
Insertar datos
Los datos se pueden insertar en una PrettyTable ya sea fila por fila o columna por columna .
Insertar datos fila por fila
Para hacer esto, puede establecer los nombres de los campos primero usando el atributo field_names y luego agregar las filas una a la vez usando el método add_row.
Ejemplo:
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # row by row x.field_names = ["First name", "Last name", "Salary", "City", "DOB"] x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"]) x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"]) x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"]) x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"]) x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"]) x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"]) x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # printing generated table print(x)
Producción:
Insertar datos columna por columna
Para hacer esto, utiliza el método add_column, que toma dos argumentos: una string que es el nombre del campo al que corresponde la columna que está agregando y una lista o tupla que contiene los datos de la columna.
Ejemplo:
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # column by column x.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000]) x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # printing generated table print(x)
Producción:
Eliminación de datos
Se puede eliminar una fila específica usando el método del_row(). El índice de la fila a eliminar se pasa como parámetro.
Ejemplo:
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # column by column x.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000]) x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # Deleting row x.del_row(2) x.del_row(3) # printing generated table print(x)
Producción:
Todas las filas de la tabla se pueden eliminar mediante el método clear_rows(). Este método mantendrá los nombres de las columnas. Para eliminar filas y columnas, se usa el método clear().
Ejemplo:
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # column by column x.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000]) x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # Deleting all rows x.clear_rows() print(x) # Deleting column name as well print("\nAfter clearing column names as well") x.clear() print(x)
Producción:
Controlar qué datos se muestran
Puede controlar qué filas o qué columnas se mostrarán.
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # column by column x.field_names = ["First name", "Last name", "Salary", "City", "DOB"] x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"]) x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"]) x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"]) x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"]) x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"]) x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"]) x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # With the start and end parameters, we can select # which rows to display in the output. print(x.get_string(start=2, end=4)) # With the fields option we can select columns # which are going to be displayed. print(x.get_string(fields=["First name", "Salary", "City"]))
Producción:
Varias otras operaciones que se pueden realizar
- La clasificación (ascendente o descendente) se puede realizar utilizando la propiedad sortby, en la que clasificamos la tabla especificando una columna para ordenar.
- La salida HTML de la tabla se puede generar utilizando el método get_html_string.
Python3
# importing required library from prettytable import PrettyTable # creating an empty PrettyTable x = PrettyTable() # adding data into the table # row by row x.field_names = ["First name", "Last name", "Salary", "City", "DOB"] x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"]) x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"]) x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"]) x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"]) x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"]) x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"]) x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # printing generated table print("Original Table:") print(x) # printing the HTML string of this table print("\nHTML code for this Table:") print(x.get_html_string()) # printing table after sorting(ascending) # by column salary x.sortby = "Salary" print("\nSorted Table by Salary:") print(x.get_string()) # printing table after sorting(ascending) # by column city x.sortby = "City" x.reversesort = True print("\nReverse Sorted Table by City:") print(x.get_string())
Producción:
Publicación traducida automáticamente
Artículo escrito por Shubham_Chauhan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA