Reordering the columns in a Pandas DataFrame is simple and straightforward. Example:
Table of contents
Reorder columns of a DataFrame
Let's consider the following code
import pandas as pd
import numpy as np
data = np.arange(1,21).reshape(4,5)
df = pd.DataFrame(data=data, columns=['A','C','E','D','B'])
print(df)
which returns the dataframe:
A C E D B
0 1 2 3 4 5
1 6 7 8 9 10
2 11 12 13 14 15
3 16 17 18 19 20
To rearrange the order of the columns, you simply need to specify the order of the column labels in your code. For example, if you want to reorder your current DataFrame with three columns ( ['A', 'C', 'E', 'D', 'B']) to one with the columns reordered as ['A', 'B', 'C', 'D', 'E']:
df_new = df[['A', 'B', 'C', 'D', 'E']]
print(df_new)
It's important to note that this method does not change the original dataframe; it returns a new dataframe with the desired column order.
Another example
Create a list of dataframe column names
col_names = list( df.columns )
col_names
returns here
['A', 'C', 'E', 'D', 'B']
Now sort the list using the sort() method
col_names.sort()
col_names
returns
['A', 'B', 'C', 'D', 'E']
Create a new dataframe
df_new = df[col_names]
print(df_new)
Output
A B C D E
0 1 5 2 4 3
1 6 10 7 9 8
2 11 15 12 14 13
3 16 20 17 19 18
References
Links | Site |
---|---|
sorting | docs.python.org |