Home » Pandas: How to Move Column to Front of DataFrame

Pandas: How to Move Column to Front of DataFrame

by Erma Khan

You can use the following methods to move columns to the front of a pandas DataFrame:

Method 1: Move One Column to Front

df = df[['my_col'] + [x for x in df.columns if x != 'my_col']]

Method 2: Move Multiple Columns to Front

cols_to_move = ['my_col1', 'my_col2']

df = df[cols_to_move + [x for x in df.columns if x not in cols_to_move]]

The following examples show how to use each method with 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

Example 1: Move One Column to Front

The following code shows how to move the ‘assists’ column to the front of the DataFrame:

#move 'assists' column to front
df = df[['assists'] + [x for x in df.columns if x != 'assists']]

#view updated DataFrame
print(df)
   assists team  points  rebounds
0        5    A      18        11
1        7    B      22         8
2        7    C      19        10
3        9    D      14         6
4       12    E      14         6
5        9    F      11         5
6        9    G      20         9
7        4    H      28        12

The ‘assists’ column has been moved to the front of the DataFrame and every other column has remained in the same order.

Example 2: Move Multiple Columns to Front

The following code shows how to move both the ‘points’ and ‘rebounds’ columns to the front of the DataFrame:

#define columns to move to front
cols_to_move = ['points', 'rebounds']

#move columns to front
df = df[cols_to_move + [x for x in df.columns if x not in cols_to_move]]

#view updated DataFrame
print(df)

   points  rebounds team  assists
0      18        11    A        5
1      22         8    B        7
2      19        10    C        7
3      14         6    D        9
4      14         6    E       12
5      11         5    F        9
6      20         9    G        9
7      28        12    H        4

The ‘points’ and ‘rebounds’ columns have both been moved to the front of the DataFrame.

Additional Resources

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

How to Insert a Column Into a Pandas DataFrame
How to Drop the Index Column in Pandas
How to Combine Two Columns in Pandas

Related Posts