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 negativenvalue returns all rows except the firstnrows. In the negativecase, it acts like index n [n:].
Syntax
# Signature according to documentationDataFrame.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 moduleimport pandas as pd# Making the DataFramedf = pd.read_csv("data.csv")# Calling the tail() method without argumentsbottom_observations = df.tail()# Displaying the resultprint(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 thebottom_observationsvariable. - 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 moduleimport pandas as pd# Making the DataFramedf = pd.read_csv("data.csv")# Calling the tail() method without argumentsbottom_observations = df.tail(10)# Displaying the resultsprint(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 thebottom_observationsvariable. - Line 8: We print the last ten observations of the
dfDataFrame.