Write a Python program to reshape a given dataframe in different ways


We can reshape a dataframe using melt(),stack(),unstack() and pivot() function.

Solution 1

  • Define a dataframe.

  • Apply melt() function to convert wide dataframe column as rows. It is defined below,

df.melt()

Example

Let’s see the below code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3],'Age':[13,14,13],'Mark':[80,90,85]})
print("Dataframe is:\n",df)
print(df.melt())

Output

Dataframe is:
 Id Age Mark
0 1 13   80
1 2 14   90
2 3 13   85
variable value
0    Id    1
1    Id    2
2    Id    3
3   Age    13
4   Age    14
5   Age    13
6   Mark   80
7   Mark   90
8   Mark   85

Solution 2

  • Define a dataframe.

  • Apply stack() function to increase the level of the index in a dataframe. It is defined below,

df.stack().to_frame()
  • If you want to revert back the changes, you can use unstack().

df.unstack().to_frame()

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3],'Age':[13,14,13],'Mark':[80,90,85]})
print("Dataframe is:\n",df)
print(df.stack().to_frame())
print(df.unstack().to_frame())

Output

Dataframe is:
   Id   Age Mark
0   1    13  80
1   2    14  90
2   3    13  85
          0
0   Id    1
   Age    13
   Mark   80
1   Id     2
   Age    14
  Mark    90
2   Id    3
   Age    13
   Mark   85
          0
Id   0    1
     1    2
     2    3
Age  0    13
     1    14
     2    13
Mark 0    80
     1    90
     2    85

Solution 3

  • Define a dataframe

  • Apply pivot() function to reshape a dataframe based on Id column,

df.pivot(columns='Id')

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3],'Age':[13,14,13],'Mark':[80,90,85]})
print("Dataframe is:\n",df)
print(df.pivot(columns='Id'))

Output

Dataframe is:
 Id Age Mark
0 1 13   80
1 2 14   90
2 3 13   85
      Age          Mark
Id    1    2    3    1    2    3
0   13.0  NaN  NaN  80.0 NaN  NaN
1   NaN  14.0  NaN  NaN  90.0 NaN
2   NaN  NaN   13.0 NaN  NaN  85.0

Updated on: 25-Feb-2021

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements