How do you Swap Two Rows in Pandas?

In order to swap two rows in Pandas, the user can use the loc functionality, which is the primary access method in Pandas. This involves setting the row indices of the two rows to be swapped, and then using the loc to reassign the values for those indices. This operation can be done in two lines of code, and the result will be that the two rows have been swapped.


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 function to select rows in the DataFrame based on their index position.

x