How to Change the Order of Columns in Pandas DataFrame


You can use the following syntax to quickly change the order of columns in a pandas DataFrame:

df[['column2', 'column3', 'column1']]

The following examples show how to use this syntax with the following pandas DataFrame:

import pandas as pd

#create new DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#display DataFrame
df

	points	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6
5	23	9	5
6	25	9	9
7	29	4	12

Example 1: Change the Order of Columns by Name

The following code shows how to change the order of the columns in the DataFrame based on name:

#change order of columns by name
df[['rebounds', 'assists', 'points']]

	rebounds assists points
0	11	 5	 25
1	8	 7	 12
2	10	 7	 15
3	6	 9	 14
4	6	 12	 19
5	5	 9	 23
6	9	 9	 25
7	12	 4	 29

Example 2: Change the Order by Adding New First Column

The following code shows how to change the order of the columns in the DataFrame by inserting a new column in the first position:

#define new column to add
steals = [2, 3, 3, 4, 3, 2, 1, 2]

#insert new column in first position
df.insert(0, 'steals', steals)

#display dataFrame
df
        steals	points	assists	rebounds
0	2	25	5	11
1	3	12	7	8
2	3	15	7	10
3	4	14	9	6
4	3	19	12	6
5	2	23	9	5
6	1	25	9	9
7	2	29	4	12

Example 3: Change the Order by Adding New Last Column

The following code shows how to change the order of the columns in the DataFrame by inserting a new column in the last position of the DataFrame:

#define new column to add
steals = [2, 3, 3, 4, 3, 2, 1, 2]

#insert new column in last position
df.insert(len(df.columns), 'steals', steals)

#display dataFrame
df

	points	assists	rebounds steals
0	25	5	11	 2
1	12	7	8	 3
2	15	7	10	 3
3	14	9	6	 4
4	19	12	6	 3
5	23	9	5	 2
6	25	9	9	 1
7	29	4	12	 2

Additional Resources

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

Leave a Reply

Your email address will not be published.