How to Transpose an Array in Python?

Recently in a project for USA clients, I got a scenario to transpose an array in Python, that deals with matrices and two-dimensional arrays. Python provides several ways to transpose arrays, Let us explore different methods and provide examples to help you understand.

What is Array Transposition in Python

Before we get into the code, let us understand what is Python array transposition. In simple words, I can say, transposing an array is swapping its rows and columns. Consider you have a 2D array with 3 rows and 4 columns, transposing would result in an array with 4 rows and 3 columns. The elements in the original array are rearranged such that the element at position (i, j) in the original array becomes the element at position (j, i) in the transposed array.

Consider the following example:

original_array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

After transposing, the array would become:

transposed_array = [
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]
]

Check out How to Find the Number of Elements in a Python Array

Transpose Python Arrays Using NumPy

The easiest and most efficient way to transpose an array in Python is by using the NumPy library. NumPy provides transpose() function that allows you to easily transpose arrays of any dimension. Let’s see how it works.

First, make sure you have NumPy installed. You can install it using pip:

pip install numpy

Now, let’s import NumPy and create an array to transpose:

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

To transpose the array, use the transpose() function:

transposed_arr = np.transpose(arr)

The transposed_arr will contain the transposed array of the original array.

Let’s put it together in an example:

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

print("Original array:")
print(arr)

# Transpose the array
transposed_arr = np.transpose(arr)

print("Transposed array:")
print(transposed_arr)

Output:

Original array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Transposed array:
[[1 4 7]
 [2 5 8]
 [3 6 9]]

Look at the executed example code in the screenshot below.

Transpose an Array in Python

As you can see, the transpose() function efficiently transposes the array, by swapping the rows and columns.

Read How to Save an Array to a File in Python

Transpose Python Arrays Using List Comprehension

If you do not want to use NumPy or want to understand how to transpose arrays using pure Python, you can use list comprehension. List comprehension allows you to create new lists based on existing lists or arrays.

Here’s an example of transposing a 2D array using list comprehension:

# Create a 2D array
arr = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]

# Transpose the array using list comprehension
transposed_arr = [[row[i] for row in arr] for i in range(len(arr[0]))]

print("Original array:")
print(arr)

print("Transposed array:")
print(transposed_arr)

Output:

Original array:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Transposed array:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Look at the executed example code in the screenshot below.

How to Transpose an Array in Python

In this example, we have used nested list comprehension to create a new array where each row of the transposed array is created by taking elements from the corresponding column of the original array.

Check out How to Use Python Array Index -1

Transpose Python Arrays Using Loops

Another approach to transpose arrays is by using nested loops. While this method may not be as brief as using NumPy or list comprehension, it provides a clear understanding of the transposition process.

Here’s an example that demonstrates how to transpose an array using loops:

# Create a 2D array
arr = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]

rows = len(arr)
cols = len(arr[0])

# Create an empty array to store the transposed result
transposed_arr = [[0 for _ in range(rows)] for _ in range(cols)]

# Transpose the array using nested loops
for i in range(rows):
    for j in range(cols):
        transposed_arr[j][i] = arr[i][j]

print("Original array:")
print(arr)

print("Transposed array:")
print(transposed_arr)

Output:

Original array:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Transposed array:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Look at the executed example code in the screenshot below.

Transpose an Array in Python using loops

In this example, we first create an empty array transposed_arr with the dimensions swapped. Then, we use nested loops to iterate over the original array and assign each element to its corresponding position in the transposed array.

Check out How to Convert an Array to a Tuple in Python

Example

Consider a real world scenario where transposing an array can be useful. Suppose you have a dataset containing sales data for different products across various states in the USA. The data is stored in a 2D array where each row represents a product and each column represents a state.

sales_data = [
    [1000, 1500, 2000, 1200],  # Product 1 sales in California, Texas, New York, Florida
    [2500, 1800, 3000, 2200],  # Product 2 sales in California, Texas, New York, Florida
    [1800, 2200, 2500, 1900]   # Product 3 sales in California, Texas, New York, Florida
]

Now, suppose you want to analyze the sales data by state instead of by product. To do this, you can transpose the sales_data array:

transposed_sales_data = np.transpose(sales_data)

The transposed_sales_data array will have the following structure:

[
    [1000, 2500, 1800],  # California sales for Product 1, Product 2, Product 3
    [1500, 1800, 2200],  # Texas sales for Product 1, Product 2, Product 3
    [2000, 3000, 2500],  # New York sales for Product 1, Product 2, Product 3
    [1200, 2200, 1900]   # Florida sales for Product 1, Product 2, Product 3
]

With the transposed array, you can easily analyze and compare sales figures by state, allowing you to gain insights into which states generate the highest sales for each product.

Read How to Get Values from a JSON Array in Python

Conclusion

In this tutorial, I provided an in depth explanation of how to transpose an array in Python by using various methods, We also discussed what is array transposition in Python. I explained transposing Python arrays using NumPy, that is by using transpose() function, and list comprehension, by using loops.

Hope this article helped you to understand how to transpose an array in Python and can apply this knowledge to your projects. Happy coding!

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.