What is DataFrame.tail() in Pandas?

Overview

The DataFrame.tail() method in Pandas gets the last n observations or rows of a DataFrame or series.

Note: The negative n value returns all rows except the first n rows. In the negative indexn case, it acts like [n:].

Syntax


# Signature according to documentation
DataFrame.tail([n]) # default n=5
Syntax of the DataFrame

Parameter

This method takes the following argument value.

  • n: It is the number of rows to be retrieved.

Return value

This method returns a DataFrame or Series object.

Code

In the code snippet below, we load the data.csv NBA league dataset. Moreover, we process it in the form of a DataFrame.

main.py
data.csv
# Importing the Pandas module
import pandas as pd
# Making the DataFrame
df = pd.read_csv("data.csv")
# Calling the tail() method without arguments
bottom_observations = df.tail()
# Displaying the result
print(bottom_observations)

Explanation

data.csv:

This NBA league data set contains the "Name," "Team Name," "Number," "Position," "Age," "College," and "Salary" of each player as features.

main.py:

  • Line 4: We invoke the read_csv() method to load the data set as a DataFrame.
  • Line 6: We invoke the tail() method, with the default argument value as 5, from the Pandas library. This gets the last five entries in the bottom_observations variable.
  • Line 8: We print the results to the console.

Code

In the code snippet below, we extract the last ten entries from the DataFrame.

main.py
data.csv
# Importing the Pandas module
import pandas as pd
# Making the DataFrame
df = pd.read_csv("data.csv")
# Calling the tail() method without arguments
bottom_observations = df.tail(10)
# Displaying the results
print(bottom_observations)

Explanation

  • Line 4: We invoke the pd.read_csv("data.csv") method to load the data set as a DataFrame.
  • Line 6: We invoke df.tail(10) from the Pandas library to get the last ten entries in the bottom_observations variable.
  • Line 8: We print the last ten observations of the df DataFrame.

Free Resources