How to transpose a DataFrame with Pandas using Python

1 min

Transposing data might come in handy when you need to inverse the columns and index.

Using the pandas.DataFrame.transpose() method or pandas.DataFrame.T you can achieve exactly that.

Here is the code

import pandas as pd

# We generate our sample data
df = pd.DataFrame(index=["jan", "feb", "mar", "apr", "may"], 
                  data={"sales" : range(1000,6000, 1000)})
df = df.T

The result

The dataframe without transposing
The dataframe with transposing

Here you are! You now know how to transpose a DataFrame with Pandas using Python.

More on DataFrames

If you want to know more about DataFrame and Pandas. Check out the other articles I wrote on the topic, just here :

Pandas - The Python You Need
We gathered the only Python essentials that you will probably ever need.