Pandas DataFrame Transpose
Transposing a Pandas DataFrame involves swapping its rows with columns and vice versa, effectively rotating the DataFrame. This guide covers the syntax, example, output, explanation, use cases, important points, and a summary of transposing a Pandas DataFrame.
Syntax
import pandas as pd
# Transpose a DataFrame
transposed_df = original_df.T
original_df
: The original DataFrame that you want to transpose.
Example
import pandas as pd
# Creating a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)
# Transposing the DataFrame
transposed_df = df.T
# Displaying the transposed DataFrame
print(transposed_df)
Output
0 1 2
Name Alice Bob Charlie
Age 25 30 35
City New York San Francisco Los Angeles
Explanation
- The
.T
attribute is used to transpose the original DataFrame, swapping rows and columns. - Column labels become index labels, and vice versa.
Use
- Transposing is useful when you want to switch between viewing data by rows and columns.
- It can be helpful in certain data analysis and visualization scenarios.
Important Points
- Transposing does not modify the original DataFrame; it returns a new transposed DataFrame.
- Be cautious when transposing large datasets, as it creates a copy of the data.
Summary
Transposing a Pandas DataFrame is a simple operation that provides a different perspective on the data. It can be particularly useful when you want to inspect or present data in a different format. Keep in mind that transposing creates a new DataFrame, and the original data structure remains unchanged.