How to Transpose DataFrame in pandas: Simple Guide
To transpose a DataFrame in pandas, use the
.T attribute or the transpose() method. Both flip rows and columns, turning rows into columns and columns into rows.Syntax
You can transpose a pandas DataFrame using either the .T attribute or the transpose() method.
DataFrame.T: A quick attribute to transpose the DataFrame.DataFrame.transpose(): A method that does the same and allows optional parameters.
python
transposed_df = df.T
# or
transposed_df = df.transpose()Example
This example shows how to create a simple DataFrame and transpose it using both .T and transpose(). The output shows rows and columns swapped.
python
import pandas as pd # Create a sample DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob'], 'Age': [25, 30], 'City': ['NY', 'LA'] }) # Transpose using .T transposed1 = df.T # Transpose using transpose() transposed2 = df.transpose() print('Original DataFrame:') print(df) print('\nTransposed with .T:') print(transposed1) print('\nTransposed with transpose():') print(transposed2)
Output
Original DataFrame:
Name Age City
0 Alice 25 NY
1 Bob 30 LA
Transposed with .T:
0 1
Name Alice Bob
Age 25 30
City NY LA
Transposed with transpose():
0 1
Name Alice Bob
Age 25 30
City NY LA
Common Pitfalls
One common mistake is expecting the transpose to change the original DataFrame. It returns a new DataFrame and does not modify the original unless reassigned.
Also, transposing DataFrames with mixed data types can lead to unexpected data type changes because pandas tries to align data types in columns.
python
import pandas as pd df = pd.DataFrame({ 'A': [1, 2], 'B': ['x', 'y'] }) # Wrong: expecting original df to change _ = df.T print(df) # df is unchanged # Right: reassign to keep transposed df = df.T print(df)
Output
A B
0 1 x
1 2 y
0 1
A 1 2
B x y
Quick Reference
Use .T for quick transpose without parameters.
Use transpose() if you want to specify axes (rarely needed).
| Method | Description | Example |
|---|---|---|
| .T | Transpose DataFrame quickly | df.T |
| transpose() | Transpose with optional axes | df.transpose() |
Key Takeaways
Use df.T or df.transpose() to transpose a pandas DataFrame.
Transposing swaps rows and columns but does not change the original DataFrame unless reassigned.
Mixed data types in DataFrame columns may affect the result after transpose.
Use .T for simple transpose and transpose() for more control if needed.