Change Order of Columns in Pandas DataFrame


Change Order of DataFrame Columns in Pandas

You can change the order of columns in a DataFrame by using DataFrame.reindex(), DataFrame indexing technique, or DataFrame constructor.

1. Change order of columns 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)

Output

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

2. Change order of columns 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)

Output

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

3. Change order of columns 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)

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.