Swap Rows and Columns in Python Tabulate: Data Transposition
When working with tabular data in Python, you might need to swap rows and columns to better present your data.
This tutorial shows how to swap rows and columns using different methods and display the results with tabulate
.
Using Python zip Function
You can use the built-in zip
function to transpose your data before passing it to tabulate
.
from tabulate import tabulate data = [ ['Amina', 28, 'Engineer'], ['Hassan', 35, 'Doctor'], ['Laila', 26, 'Teacher'] ] headers = ['Name', 'Age', 'Profession'] print("Original Table:") print(tabulate(data, headers=headers)) # Transpose the data using zip transposed_data = list(zip(*data)) print("\nTransposed Table:") print(tabulate(transposed_data))
Output:
Original Table: Name Age Profession ------ ----- ------------ Amina 28 Engineer Hassan 35 Doctor Laila 26 Teacher Transposed Table: -------- ------ ------- Amina Hassan Laila 28 35 26 Engineer Doctor Teacher -------- ------ -------
In the original table, each row represents a person with their details. After transposing, each column represents a person’s details.
Using NumPy transpose Function
You can use NumPy transpose
function to swap rows and columns:
import numpy as np from tabulate import tabulate # Convert data to a NumPy array np_data = np.array(data) print("Original Table:") print(tabulate(np_data, headers=headers)) # Transpose the array transposed_data = np_data.T print("\nTransposed Table:") print(tabulate(transposed_data))
Output:
Original Table: Name Age Profession ------ ----- ------------ Amina 28 Engineer Hassan 35 Doctor Laila 26 Teacher Transposed Table: -------- ------ ------- Amina Hassan Laila 28 35 26 Engineer Doctor Teacher -------- ------ -------
The T
attribute transposes the array and swaps rows and columns.
Using pandas DataFrame transpose Method
The DataFrame transpose()
method allows you to swap rows and columns:
import pandas as pd from tabulate import tabulate # Create a DataFrame from the data df = pd.DataFrame(data, columns=headers) print("Original Table:") print(tabulate(df, headers='keys', tablefmt='github', showindex=False)) # Transpose the DataFrame df_transposed = df.transpose() print("\nTransposed Table:") print(tabulate(df_transposed, headers='keys', tablefmt='github'))
Output:
Original Table: | Name | Age | Profession | |--------|-------|--------------| | Amina | 28 | Engineer | | Hassan | 35 | Doctor | | Laila | 26 | Teacher | Transposed Table: | | 0 | 1 | 2 | |------------|------------|----------|----------| | Name | Amina | Hassan | Laila | | Age | 28 | 35 | 26 | | Profession | Engineer | Doctor | Teacher |
Using List Comprehension
List comprehension allows you to transpose data without importing additional modules.
from tabulate import tabulate transposed_data = [[row[i] for row in data] for i in range(len(data[0]))] print("Transposed Table:") print(tabulate(transposed_data))
Output:
Transposed Table: -------- ------ ------- Amina Hassan Laila 28 35 26 Engineer Doctor Teacher -------- ------ -------
By iterating over the indices of the inner lists, you extract elements at each position and group them together.
Using itertools.zip_longest for Uneven Lists
When dealing with lists of different lengths, itertools.zip_longest
ensures all elements are included during transposition.
from tabulate import tabulate from itertools import zip_longest data_uneven = [ ['Ahmed', 40, 'Architect'], ['Fatima', 30], ['Youssef', 25, 'Lawyer', 'Cairo'] ] headers = ['Name', 'Age', 'Profession', 'City'] print("Original Table:") print(tabulate(data_uneven, headers=headers)) transposed_data = list(zip_longest(*data_uneven, fillvalue='N/A')) print("\nTransposed Table:") print(tabulate(transposed_data))
Output:
Original Table: Name Age Profession City ------- ----- ------------ ------ Ahmed 40 Architect Fatima 30 Youssef 25 Lawyer Cairo Transposed Table: --------- ------ ------- Ahmed Fatima Youssef 40 30 25 Architect N/A Lawyer N/A N/A Cairo --------- ------ -------
Using zip_longest
allows you to handle lists of different lengths by filling missing values with a placeholder such as 'N/A'
.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.