Numpy Transpose: Implementation with Steps

The numpy transpose function in python allows you to transpose a numpy array. This function reverses the axis of the array. It means rows becomes columns and vice-versa. In this tutorial you will know how to use numpy transpose function through steps.

Steps to Implement Numpy Transpose Function

Transposing a NumPy array involves switching its rows and columns. The numpy.transpose function is commonly used for this operation. Below are the steps to implement NumPy transpose.

Step 1: Import NumPy module

import numpy as np

Step 2: Create a NumPy array

The next step is to create a sample 2D Numpy array.

# Example array
original_array = np.array([[10, 20, 30],
                           [40, 50, 60],
                           [70, 80, 90]])

Step 3: Use numpy.transpose function

# Transpose the array
transposed_array = np.transpose(original_array)
# Alternatively, you can use the T attribute
# transposed_array = original_array.T

Step 4: Display the result

print("Original Array:")
print(original_array)

print("\nTransposed Array:")
print(transposed_array)

Below is the entire code for the above steps.

Full Code

import numpy as np

# Step 2: Create a NumPy array
original_array = np.array([[10, 20, 30],
                           [40, 50, 60],
                           [70, 80, 90]])

# Step 3: Use numpy.transpose function
transposed_array = np.transpose(original_array)
# Alternatively, you can use the T attribute
# transposed_array = original_array.T

# Step 4: Display the result
print("Original Array:")
print(original_array)

print("\nTransposed Array:")
print(transposed_array)

Running this code will output the original array and its transpose.

Original Array:
[[10 20 30]
 [40 50 60]
 [70 80 90]]

Transposed Array:
[[10 40 70]
 [20 50 80]
 [30 60 90]]

Conclusion

You may require to transpose the matrix often. The above steps use the numpy.transpose function to transpose the numpy array. You can also use the numpy.T shorthand to transpose the NumPy array.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link