how to transpose a pandas dataframe in python

To transpose a Pandas DataFrame in Python, you can use the transpose() function or the .T attribute.

Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John', 'Emma', 'Ryan'],
        'Age': [26, 24, 30],
        'Country': ['USA', 'Canada', 'UK']}
df = pd.DataFrame(data)

# Transpose the DataFrame using the transpose() function
transposed_df = df.transpose()
print(transposed_df)

# Transpose the DataFrame using the .T attribute
transposed_df = df.T
print(transposed_df)
390 chars
16 lines

Both transpose() function and .T attribute will return a new transposed DataFrame. The result will be a DataFrame where the columns of the original DataFrame become rows, and vice versa.

Note that the transposed DataFrame will have the column names of the original DataFrame as index.

Output:

main.py
           0       1     2
Name    John    Emma  Ryan
Age       26      24    30
Country  USA  Canada    UK

           0       1     2
Name    John    Emma  Ryan
Age       26      24    30
Country  USA  Canada    UK
217 chars
10 lines

related categories

gistlibby LogSnag