Python Pandas program to remove the last n rows of a given DataFrame

In this python pandas program, we will remove the last n rows of a given DataFrame using the pandas library.

Steps to solve the program
  1. Import pandas library as pd.
  2. Create a dataframe using pd.DataFrame().
  3. Create a new dataframe by after removing the first 2 rows using df1 = df.iloc[:2].
  4. Print the output.
				
					import pandas as pd
import numpy as np
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(df)
print("After removing last 2 rows of the DataFrame:")
df1 = df.iloc[:2]
print(df1)
				
			

Output :

				
					0   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 removing last 2 rows of the DataFrame:
   Sr.no.  Name  Age  Salary
0       1  Alex   30   50000
1       2  John   27   65000
				
			

remove the first n rows of a DataFrame

reverse the order of rows of a given DataFrame

Leave a Comment