Python Pandas program to sort the DataFrame by a column

In this python pandas program, we will sort the DataFrame by a column using pandas library.

Steps to solve the program
  1. Import pandas library as pd.
  2. Create a dataframe using pd.DataFrame().
  3. Sort the DataFrame by age column in ascending order using df.sort_values(by=[‘Age’], ascending=[True]).
  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]}
df = pd.DataFrame(d)
print("Original Series: ")
print(df)
new = df.sort_values(by=['Age'], ascending=[True])
print("After sorting: ")
print(new)
				
			

Output :

				
					Original Series: 
   Sr.no.   Name  Age
0       1   Alex   30
1       2   John   27
2       3  Peter   29
3       4  Klaus   33
After sorting: 
   Sr.no.   Name  Age
1       2   John   27
2       3  Peter   29
0       1   Alex   30
3       4  Klaus   33
				
			

calculate the mean of age column

replace the value in a row

Leave a Comment