Write a Python code to swap last two rows in a given dataframe


Assume you have dataframe and the result for swapping last two rows,

Before swapping
  Name    Age Maths Science English
0 David   13   98      75    79
1 Adam    12   59      96    45
2 Bob     12   66      55    70
3 Alex    13   95      49    60
4 Serina  12   70      78    80
After swapping
   Name  Age Maths Science English
0 David   13   98    75    79
1 Adam    12   59    96    45
2 Bob     12   66    55    70
3 Serina  12   70    78    80
4 Alex    13   95    49    60

Solution

To solve this, we will follow the approach given below −

  • Define a dataframe

  • Create temp data to store last row. It is defined below,

temp = df.iloc[-1]
  • Swap second row values to first row and assign temp data to second row. It is defined below,

df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp

Example

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

import pandas as pd
data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
         'Age' : [13,12,12,13,12],
         'Maths': [98, 59, 66, 95, 70],
         'Science': [75, 96, 55, 49, 78],
         'English': [79, 45, 70, 60, 80]}
df = pd.DataFrame(data)
print("Before swapping\n",df)
temp = df.iloc[-1]
df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp
print("After swapping\n",df)

Output

Before swapping
  Name    Age Maths Science English
0 David   13    98    75    79
1 Adam    12    59    96    45
2 Bob     12    66    55    70
3 Alex    13    95    49    60
4 Serina  12    70    78    80
After swapping
   Name   Age Maths Science English
0 David    13   98    75    79
1 Adam     12   59    96    45
2 Bob      12   66    55    70
3 Serina   12   70    78    80
4 Alex    13    95    49    60

Updated on: 24-Feb-2021

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements