How to Transpose a DataFrame in Pandas

Spread the love

The T and transpose method in pandas transposes a DataFrame. It converts the columns to Rows and Rows to Columns.

Examples –

Let’s create a DataFrame to work with.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Transpose a Pandas DataFrame using the T property –

To transpose a DataFrame in Pandas, we can use the T property.

df.T

2. Transpose a Pandas DataFrame using transpose() method –

We can also use the transpose method to transpose a dataframe in pandas.

df.transpose()

Rating: 1 out of 5.

Leave a Reply