Let’s discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:
Example:
Python3
# Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name' : [ 'Sukritin' , 'Sumit Tyagi' , 'Akriti Goel' , 'Sanskriti' , 'Abhishek Jain' ], 'Age' : [ 22 , 20 , np.inf, - np.inf, 22 ], 'Marks' : [ 90 , 84 , 33 , 87 , 82 ]} # Converting Dictionary to Pandas Dataframe df = pd.DataFrame( dict ) # Print Dataframe df |
Output:
Method 1: Using tail() method
Use pandas.DataFrame.tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end). By default n = 5, it return the last 5 rows if the value of n is not passed to the method.
Syntax:
df.tail(n)
Example:
Python3
# Getting last 3 rows from df df_last_3 = df.tail( 3 ) # Printing df_last_3 print (df_last_3) |
Output:
Method 2: Using pandas.DataFrame.iloc
Use pandas.DataFrame.iloc to get last n rows. It is similar to the list slicing.
Syntax:
df.iloc[-n:]
Example:
Python3
# Getting last 3 rows from df df_last_3 = df.iloc[ - 3 :] # Printing df_last_3 print (df_last_3) |
Output:
Method 3: Display last n records of specific columns
Display last n records for the specific column
Python3
# Getting last 2 rows of columns # Age and Marks from df df_last_2 = df[[ 'Age' , 'Marks' ]].tail( 2 ) # Printing df_last_2 print (df_last_2) |
Output:
Method 4: Display last n records from last n columns
Display last n records for the last n columns using pandas.DataFrame.iloc
Python3
# Getting last n rows and last n columns from df df_last_2_row_col = df.iloc[ - 2 :, - 2 :] # Printing df_last_2 print (df_last_2_row_col) |
Output:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.