In Python, the pandas
library has built-in functionalities to perform different tasks with only a few lines of code. One of these functionalities allows you to change the order of columns in dataframe.
In this method, we first initialize the pandas
dataframe with a sample list format "abcde"
. Then, we use the list()
function of Python to interchange the columns’ order, which will convert the given format into a specified format of list
.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframedf = pd.DataFrame(np.arange(30).reshape(-1, 5), columns=list('abcde'))#changing order of columndf = df[list('cbdea')]print(df)
In this method, we first initialise the pandas
dataframe. Then, we use the tolist()
function to convert the columns of the dataframe into a list. Afterwards, we find the index of the columns that we want to change in the dataframe. In the end, we simply swap the two columns.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframedf = pd.DataFrame(np.arange(30).reshape(-1, 5), columns=list('abcde'))#changing order of columncolumn1 = 'b'column2 = 'd'colnames = df.columns.tolist()index1, index2 = colnames.index(column1), colnames.index(column2)colnames[index2], colnames[index1] = colnames[index1], colnames[index2]df = df[colnames]print(df)
In this method, we first initialise the pandas
dataframe. We can use the sorted()
function of Python to sort the columns of the dataframe and change their order.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframedf = pd.DataFrame(np.arange(30).reshape(-1, 5), columns=list('acdbe'))#changing the order of columndf = df[sorted(df.columns)]print(df)
In this method, we first initialise the pandas
dataframe. Then, we apply the sort_index()
function of Python to sort the columns of the dataframe. This function sorts in ascending/descending order and along a specified axis.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframedf = pd.DataFrame(np.arange(30).reshape(-1, 5), columns=list('adcbe'))#changing order of columndf.sort_index(axis=1, ascending=True, inplace=True)print(df)