How to change Order of Columns in Pandas DataFrame?

Change Order of DataFrame Columns in Pandas

Method 1 – Using DataFrame.reindex()

You can change the order of columns by calling DataFrame.reindex() on the original dataframe with rearranged column list as argument.

new_dataframe = dataframe.reindex(columns=['a', 'c', 'b'])

The reindex() function returns a new DataFrame with the given order of columns.

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd

#initialize a dataframe
df = pd.DataFrame(
	[[21, 72, 67],
	[23, 78, 62],
	[32, 74, 54],
	[52, 54, 76]],
	columns=['a', 'b', 'c'])

#change order of columns
df_new = df.reindex(columns=['a', 'c', 'b'])

#print new dataframe
print(df_new)
Run

Output

    a   c   b
0  21  67  72
1  23  62  78
2  32  54  74
3  52  76  54

Method 2 – Using DataFrame Indexing

DataFrame indexing can be used change the order of columns in a given DataFrame.

Following is the syntax to use DataFrame indexing.

new_dataframe = dataframe[['a', 'c', 'b']]

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd

#initialize a dataframe
df = pd.DataFrame(
	[[21, 72, 67],
	[23, 78, 62],
	[32, 74, 54],
	[52, 54, 76]],
	columns=['a', 'b', 'c'])

#change order of columns
df_new = df[['a', 'c', 'b']]

#print new dataframe
print(df_new)
Run

Output

    a   c   b
0  21  67  72
1  23  62  78
2  32  54  74
3  52  76  54

Method 3 – Using DataFrame Constructor

You can also use DataFrame Constructor to rearrange the order of columns. Consider the existing DataFrame as raw data, and create a new DataFrame, with this raw data and desired order of columns.

Following is the syntax to create a DataFrame with updated column order.

new_dataframe = pd.dataframe(raw_data, index=['a', 'c', 'b'])

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd

#initialize a dataframe
df = pd.DataFrame(
	[[21, 72, 67],
	[23, 78, 62],
	[32, 74, 54],
	[52, 54, 76]],
	columns=['a', 'b', 'c'])

#change order of columns
df_new = pd.DataFrame(df, columns=['a', 'c', 'b'])

#print new dataframe
print(df_new)
Run

Output

    a   c   b
0  21  67  72
1  23  62  78
2  32  54  74
3  52  76  54

Summary

In this Python Tutorial, we learned how to change the order of columns in DataFrame.