How to transpose a DataFrame in Pandas

In this tutorial, we will learn how to transpose a DataFrame in Python using a library called pandas.

Pandas library in Python is a very powerful tool for data manipulation and analysis used by data scientists and analysts across the globe. With the help of pandas, we can create a data structure called DataFrame. A DataFrame is a tabular form of the data present in CSV, excel, etc types of files. Creating a DataFrame using pandas eases out the process of data cleaning and sorting. Let us first install pandas.

pip install pandas

This command installs pandas in our computer. Now, we need to import it in our IDE or text editor.

import pandas as pd

Now, pandas is imported and ready to use. Let us make a DataFrame which we wish to transpose.

name = ['John', 'Paul', 'George', 'Ringo']
rno = ['2', '3', '1', '4']
mks = ['60', '80', '90', '75']

dict = {'Name':name, 'Rollno':rno, 'Marks':mks}

This is the data which we want to convert into a DataFrame. To do that, we use the pandas.Dataframe() method which is in-built in pandas.

df = pd.Dataframe(dict)


     Name Rollno Marks
0    John      2    60
1    Paul      3    80
2  George      1    90
3   Ringo      4    75

Here, we have created a DataFrame and stored it in a variable called df.

Moving on, to transpose this DataFrame we need to use another in-built pandas function Dataframe.transpose().

transposed_df = df.transpose()


           0     1       2      3
Name    John  Paul  George  Ringo
Rollno     2     3       1      4
Marks     60    80      90     75

As a result, we have successfully transposed our DataFrame using in-built pandas functions.

Leave a Reply

Your email address will not be published. Required fields are marked *