Python Pandas – Rearrange columns within a data frame

In this post we will be creating a Python script that will rearrange the column order within a Pandas data frame. Pandas is a Python library which is an amazing tool for data analysis and manipulation.

See a sample of our data in the image below where we have ‘Rank’, ‘Name’ and ‘Platform’.

For this example we will be rearraigning the columns in the following order ‘Name’, ‘Platform’, ‘Rank’. See the snippet of code below for how this is done.

df = df[['Name', 'Platform', 'Rank']]
print(df)

This would return the following as output.

                        Name Platform  Rank
0                 Wii Sports      Wii     1
1          Super Mario Bros.      NES     2
2             Mario Kart Wii      Wii     3
3          Wii Sports Resort      Wii     4
4   Pokemon Red/Pokemon Blue       GB     5
5                     Tetris       GB     6
6      New Super Mario Bros.       DS     7
7                   Wii Play      Wii     8
8  New Super Mario Bros. Wii      Wii     9
9                  Duck Hunt      NES    10
>>> 

Leave a Reply