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.
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)
Line 2: We import pandas
library as pd
.
Lines 4–10: We load a sample DataFrame by using the from_dict
library.
Line 13: We print a DataFrame.
We have multiple methods for reordering the columns in the pandas
library.
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)
iloc
method of reorderingNow 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)
loc
method for reorderingNow 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)
reverse()
function for reorderingIn 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