5.3 C
London
Thursday, December 19, 2024
HomePandas in PythonGeneral Functions in PythonHow to Swap Two Rows in Pandas (With Example)

How to Swap Two Rows in Pandas (With Example)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following custom function to swap the position of two rows in a pandas DataFrame:

def swap_rows(df, row1, row2):
    df.iloc[row1], df.iloc[row2] =  df.iloc[row2].copy(), df.iloc[row1].copy()
    return df

This function will swap the positions of rows in index positions row1 and row2 in the DataFrame.

The following example shows how to use this function in practice.

Example: Swap Two Rows in Pandas

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team' : ['Mavs', 'Nets', 'Kings', 'Cavs', 'Heat', 'Magic'],
                   'points' : [12, 15, 22, 29, 24, 22],
                   'assists': [4, 5, 10, 8, 7, 10]})

#view DataFrame
print(df)

    team  points  assists
0   Mavs      12        4
1   Nets      15        5
2  Kings      22       10
3   Cavs      29        8
4   Heat      24        7
5  Magic      22       10

We can define a swap_rows() function to swap the rows in index positions 0 and 4 in the DataFrame:

#define function to swap rows
def swap_rows(df, row1, row2):
    df.iloc[row1], df.iloc[row2] =  df.iloc[row2].copy(), df.iloc[row1].copy()
    return df

#swap rows in index positions 0 and 4
df = swap_rows(df, 0, 4)

#view updated DataFrame
print(df)

    team  points  assists
0   Heat      24        7
1   Nets      15        5
2  Kings      22       10
3   Cavs      29        8
4   Mavs      12        4
5  Magic      22       10

Notice that the rows in index positions 0 and 4 have been swapped while every other row has remained in the same position.

Note: Within the swap_rows() function, we used the .iloc function to select rows in the DataFrame based on their index position.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Count Occurrences of Specific Value in Column
Pandas: Get Index of Rows Whose Column Matches Value
Pandas: How to Count Missing Values in DataFrame

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories