Pandas Tutorial Pandas References

Pandas DataFrame - tail() function



The Pandas DataFrame tail() function returns the last n rows of the dataframe. The syntax for using this function is given below:

Syntax

DataFrame.tail(n)

Parameters

n Required. Specify number of rows to select.

Return Value

Returns the last n rows of the dataframe.

Example:

In the example below, a DataFrame df is created. The tail() function returns last selected number of rows of the dataframe.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4, 3, 4],
  "Last Salary": [58, 60, 63, 57, 62, 59],
  "Salary": [60, 62, 65, 59, 63, 62]},
  index= ["John", "Marry", "Sam", "Jo", "Ramesh", "Kim"]
)

print("The DataFrame is:")
print(df)

#returning last two rows of the dataframe
print("\ndf.tail(2) returns:")
print(df.tail(2))

The output of the above code will be:

The DataFrame is:
        Bonus  Last Salary  Salary
John        5           58      60
Marry       3           60      62
Sam         2           63      65
Jo          4           57      59
Ramesh      3           62      63
Kim         4           59      62

df.tail(2) returns:
        Bonus  Last Salary  Salary
Ramesh      3           62      63
Kim         4           59      62

Example:

n can take negative values as Python supports negative indexing. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4, 3, 4],
  "Last Salary": [58, 60, 63, 57, 62, 59],
  "Salary": [60, 62, 65, 59, 63, 62]},
  index= ["John", "Marry", "Sam", "Jo", "Ramesh", "Kim"]
)

print("The DataFrame is:")
print(df)

#using negative indexing with the dataframe
print("\ndf.tail(-2) returns:")
print(df.tail(-2))

The output of the above code will be:

The DataFrame is:
        Bonus  Last Salary  Salary
John        5           58      60
Marry       3           60      62
Sam         2           63      65
Jo          4           57      59
Ramesh      3           62      63
Kim         4           59      62

df.tail(-2) returns:
        Bonus  Last Salary  Salary
Sam         2           63      65
Jo          4           57      59
Ramesh      3           62      63
Kim         4           59      62

❮ Pandas DataFrame - Functions