You can use the following custom function to swap the position of two columns in a pandas DataFrame:
def swap_columns(df, col1, col2): col_list = list(df.columns) x, y = col_list.index(col1), col_list.index(col2) col_list[y], col_list[x] = col_list[x], col_list[y] df = df[col_list] return df
This function will swap the positions of columns col1 and col2 in the DataFrame.
The following example shows how to use this function in practice.
Example: Swap Two Columns in Pandas
Suppose we have the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
We can define a swap_columns() function to swap the positions of the “points” and “rebounds” columns:
#define function to swap columns def swap_columns(df, col1, col2): col_list = list(df.columns) x, y = col_list.index(col1), col_list.index(col2) col_list[y], col_list[x] = col_list[x], col_list[y] df = df[col_list] return df #swap points and rebounds columns df = swap_columns(df, 'points', 'rebounds'): #view updated DataFrame print(df) team rebounds assists points 0 A 11 5 18 1 B 8 7 22 2 C 10 7 19 3 D 6 9 14 4 E 6 12 14 5 F 5 9 11 6 G 9 9 20 7 H 12 4 28
Notice that the “points” and “rebounds” columns have been swapped while every other column has remained in the same position.
Additional Resources
The following tutorials explain how to perform other common operations 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