Open In App

Pandas DataFrame transpose() Method – Swap Rows and Columns

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Transposing a Pandas DataFrame means switching rows and columns. That means row labels become column headers and column headers become row labels. It is useful when we want to change orientation of our data for better readability and analysis. In this article, we will see some examples to understand it better.

Syntax: DataFrame.transpose(*args, **kwargs)

  • args, kwargs: Optional arguments which are not needed for basic use.

Example 1: Basic Transpose

Here we are creating a simple DataFrame and transposing it. We will implement it using Pandas library.

Python
import pandas as pd
data = {'Name': ['ANSH', 'VANSH'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
transposed_df = df.transpose()
print("\nTransposed DataFrame:")
print(transposed_df)

Output:

transpose1

Basic Transpose

This example shows how rows become columns and vice versa.

Example 2: Transposing Specific Columns

We can also transpose specific columns by specifying them while transposing.

Python
import pandas as pd
data = {'Fee': [22000, 25000], 'Duration': [3, 4]}
df = pd.DataFrame(data)
transposed_fee = df[['Fee']].transpose()
print(transposed_fee)

Output:

transpose2

Transposing specific column

Example 3: Transposing with Mixed Data Types and DateTime Index

If the DataFrame contains mixed data types and custom indices transposing works in the same way.

Python
import pandas as pd
df = pd.DataFrame({
    'Weight': [45, 88, 56, 15, 71],
    'Name': ['DEV', 'ANSHIKA', 'FARHAN', 'SHRIDHAR', 'VAMIKA'],
    'Age': [14, 25, 55, 8, 21]
}, index=pd.date_range('2010-10-09 08:45', periods=5, freq='h'))
print("Original DataFrame:")
print(df)
transposed_df = df.transpose()
print("\nTransposed DataFrame:")
print(transposed_df)

Output:

trasnpose-3

Transposing Mixed Data Types

Example 4: Handling Missing Values in Transpose

The transpose() function also handles missing values in the same way as other operation.

Python
import pandas as pd
df = pd.DataFrame({"A": [12, 4, 5, None, 1],"B": [7, 2, 54, 3, None],"C": [20, 16, 11, 3, 8],"D": [14, 3, None, 2, 6]},
                  index=['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'])
print("Original DataFrame:")
print(df)
transposed_df = df.transpose()
print("\nTransposed DataFrame:")
print(transposed_df)

Output:

transpose-4

Handling Missing Values

Transposing a DataFrame is simple in Pandas library which allows us to quickly change the way our data is structured and helps in exploring it from a different perspective.



Similar Reads