Contents
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.
Related Tutorials
- How to Sort DataFrame by Column in Pandas?
- How to Change Datatype of Columns in Pandas DataFrame?
- How to Delete Column from Pandas DataFrame?
- How to Change Column Labels in Pandas DataFrame?
- How to get Datatypes of Columns in Pandas DataFrame?
- How to Add Column to Pandas DataFrame?
- How to Get Columns of Numeric Datatype from DataFrame?
- How to Get Column Names of Pandas DataFrame?
- Pandas DataFrame – Select Column
- How to Delete Column(s) of Pandas DataFrame?