How to reorder columns in pandas
Pandas is one of the most famous tools in the data sciences field. We have a built-in library for data manipulation and analysis in Python. We can easily clean, process, and manipulate data stored in the data frame; pandas give several methods and functions. The DataFrame consists of rows and columns, which are easily accessible by using the Python library. We can also change the order of the rows and columns by using pandas. Here we specifically discuss the reordering of the columns.
Import libraries and load the DataFrame
Now, first of all, we import the pandas library and load the data frame which we will use for reordering.
# Import the library and assign variable to this libraryimport pandas as pd# Load a sample data framedata = pd.DataFrame.from_dict({'Username' : ['A', 'B', 'C', 'D', 'E'],'Gender' : ['Male', 'Female', 'Female', 'Male', 'Male'],'Age' : [15, 18, 16, 14, 15],'Score' : [8, 9, 7, 8, 6]})# print the data frameprint (data)
Code explanation
Line 2: We import
pandaslibrary aspd.Lines 4–10: We load a sample DataFrame by using the
from_dictlibrary.Line 13: We print a DataFrame.
Reorder columns by using the pandas library
We have multiple methods for reordering the columns in the pandas library.
Method 1: Direct way for reordering
We can directly reorder the columns by shuffling the column's name in the DataFrame.
# Data frame's column reshuffledt = data[['Username','Score', 'Age', 'Gender']]# print the data frameprint (dt)
Method 2: The iloc method of reordering
Now we are using the iloc method for reordering the column. In this method, we will use the index of the Dataframe to change the order of the column.
# use iloc methoddt = data.iloc[:,[0,3,1,2]]# print the data frameprint (dt)
Method 3: The loc method for reordering
Now we are using the loc method for reordering the column. In this method, we will use the column names of the DataFrame to change the order of the column.
# use loc methoddt = data.loc[:,['Age','Gender','Username','Score']]# print the data frameprint (dt)
Method 4: The reverse() function for reordering
In this method, we will use the reverse function for reordering the column.
# use the reverse functionscol = list(data.columns)col.reverse()# print the data frameprint(data[col])
Here, we have discussed four methods for reordering the column, we can use any of them according to the situation.
Free Resources