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