Pandas DataFrame transpose() Method - Swap Rows and Columns
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.
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:

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.
import pandas as pd
data = {'Fee': [22000, 25000], 'Duration': [3, 4]}
df = pd.DataFrame(data)
transposed_fee = df[['Fee']].transpose()
print(transposed_fee)
Output:

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.
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:

Example 4: Handling Missing Values in Transpose
The transpose() function also handles missing values in the same way as other operation.
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:

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.