How to Choose Last 3 Rows of Dataframe in Python

To get the last 3 rows of a dataframe in Python, you can use the iloc() function along with negative indexing.

The following example shows how to get the last 3 rows of a dataframe using the iloc() function in Python.

Using iloc() Function

We can use the iloc() function to select the last 3 rows of a dataframe.

Suppose we have the following dataframe:

# Importing pandas library
import pandas as pd

# Creating a dataframe
Office_Stuff = pd.DataFrame({
   'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
   'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
   'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
   'Price': [4500, 550, 250, 50, 350, 50],
   'Status': [1, 1, 1, 0, 1, 1]
})

# Selecting last 3 rows of dataframe
last_3_rows = Office_Stuff.iloc[-3:]

# Printing the last 3 rows of dataframe
print(last_3_rows)

Output: 👇️

         Date Product_Code Product_Name  Price  Status
3  01-03-2023        B-101     Keyboard     50       0
4  02-03-2023        B-102      Scanner    350       1
5  02-03-2023        B-104        Mouse     50       1

In this example, we use the iloc() function to select the last 3 rows of the dataframe Office_Stuff.

Conclusion

We can use the iloc() function along with negative indexing to choose the last 3 rows of a dataframe in Python. This method provides a convenient way to access specific rows from the end of a dataframe.