Python — Transpose Dataframe Columns into Rows
Today, I was working with Python where I have to transpose some columns into rows to avoid a lot of calculations. As we know that Python has a lot of libraries and very strong communities support. That means, you can solve any problems with your dataset.
Here, I’m using a small dataset to show you that how can we use pandas library to transpose your dataframe.
In this example, I’m using class students dataset where each student has their subject in the columns with their obtained marks.
Now, we have to transpose subject columns into rows in the ‘Subject’ column and marks will be display in Marks column next to Subject within dataset-2.
Pandas melt() function is used to change the DataFrame format from wide to long. It’s used to create a specific format of the DataFrame object where one or more columns work as identifiers. All the remaining columns are treated as values and unpivoted to the row axis and only two columns — variable and value.
#import Libraries
import pandas as pd
# Creating DataFrame from dict of narray/lists. intialise data of lists
list={‘Name’:[‘Ryan’,’Arjun’,’john’,’Rosy’],
‘Class’:[‘IV’,’III’,’III’,’V’],
‘English’:[90,85,90,95],
‘Math’:[95,90,85,80],
‘Science’:[95,90,90,90]…