Python Pandas program to change the order of columns in a DataFrame

In this python pandas program, we will change the order of columns in a DataFrame using the pandas library.

Steps to solve the program
  1. Import pandas library as pd.
  2. Create a dataframe using pd.DataFrame().
  3. Change the order of columns in a DataFrame using df[[‘Sr.no.’,’Name’,’Salary’,’Age’]].
  4. Print the output.
				
					import pandas as pd
d = {'Sr.no.':[1,2,3,4],'Name':['Alex','John','Peter','Klaus'],'Age':[30,27,29,33],'Salary':[50000,65000,58000,66000]}
df = pd.DataFrame(d)
print("Original Dataframe: \n",df)
df = df[['Sr.no.','Name','Salary','Age']]
print('After re-ordering columns: \n',df)
				
			

Output :

				
					Original Dataframe: 
    Sr.no.   Name  Age  Salary
0       1   Alex   30   50000
1       2   John   27   65000
2       3  Peter   29   58000
3       4  Klaus   33   66000
After re-ordering columns: 
    Sr.no.   Name  Salary  Age
0       1   Alex   50000   30
1       2   John   65000   27
2       3  Peter   58000   29
3       4  Klaus   66000   33
				
			

rename columns of a given DataFrame

write a DataFrame to a CSV file using a tab separator

Leave a Comment