Get last n records of a Pandas DataFrame
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 pandas as pd
import numpy as np
dict = { 'Name' : [ 'Sukritin' , 'Sumit Tyagi' , 'Akriti Goel' ,
'Sanskriti' , 'Abhishek Jain' ],
'Age' : [ 22 , 20 , np.inf, - np.inf, 22 ],
'Marks' : [ 90 , 84 , 33 , 87 , 82 ]}
df = pd.DataFrame( dict )
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
df_last_3 = df.tail( 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
df_last_3 = df.iloc[ - 3 :]
print (df_last_3)
|
Output:
Method 3: Display last n records of specific columns
Display last n records for the specific column
Python3
df_last_2 = df[[ 'Age' , 'Marks' ]].tail( 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
df_last_2_row_col = df.iloc[ - 2 :, - 2 :]
print (df_last_2_row_col)
|
Output:
Last Updated :
26 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...