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

In Pandas, you can swap the last two rows of a DataFrame using iloc indexing. This technique temporarily stores one row, assigns the other row's values, and then restores the stored row.

Approach

To swap the last two rows, we follow these steps ?

  • Store the last row in a temporary variable using df.iloc[-1]
  • Assign the second-to-last row values to the last row position
  • Assign the temporary row data to the second-to-last position

Example

Let's create a DataFrame and swap its last two rows ?

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:")
print(df)

# Store the last row temporarily
temp = df.iloc[-1].copy()

# Swap the rows
df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp

print("\nAfter swapping:")
print(df)
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

How It Works

The key steps in the swapping process are ?

  • df.iloc[-1] selects the last row (index 4: Serina)
  • df.iloc[-2] selects the second-to-last row (index 3: Alex)
  • .copy() ensures we create a true copy, not just a reference

Alternative Method Using Index Values

You can also swap rows using their specific index positions ?

import pandas as pd

data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
        'Age': [13, 12, 12, 13, 12],
        'Maths': [98, 59, 66, 95, 70]}

df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)

# Get the last two index positions
last_idx = df.index[-1]
second_last_idx = df.index[-2]

# Swap using loc
df.loc[[last_idx, second_last_idx]] = df.loc[[second_last_idx, last_idx]].values

print("\nAfter swapping:")
print(df)
Original DataFrame:
     Name  Age  Maths
0   David   13     98
1    Adam   12     59
2     Bob   12     66
3    Alex   13     95
4  Serina   12     70

After swapping:
     Name  Age  Maths
0   David   13     98
1    Adam   12     59
2     Bob   12     66
3  Serina   12     70
4    Alex   13     95

Conclusion

Use iloc with negative indexing to swap the last two rows efficiently. The temporary variable approach is straightforward and works well for DataFrames of any size.

Updated on: 2026-03-25T16:18:31+05:30

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements