Pandas Tutorial Pandas References

Pandas Series - tail() function



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

Syntax

Series.tail(n)

Parameters

n Required. Specify number of rows to select.

Return Value

Returns the last n rows of the series.

Example:

In the example below, the tail() function returns last selected number of rows of the given series.

import pandas as pd
import numpy as np

x = pd.Series(["Red", "Blue", "White", "Green", "Black"])

#returning last two rows from series
print("x.tail(2) returns:")
print(x.tail(2))

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

print("\nThe DataFrame contains:")
print(df)

#returning last two rows from "Name" series/column
print("\ndf['Name'].tail(2) returns:")
print(df["Name"].tail(2))

The output of the above code will be:

x.tail(2) returns:
3    Green
4    Black
dtype: object

The DataFrame contains:
   Bonus    Name  Salary
0      5    John      60
1      3   Marry      62
2      2     Sam      65
3      4      Jo      59
4      3  Ramesh      63
5      4     Kim      62

df['Name'].tail(2) returns:
4    Ramesh
5       Kim
Name: Name, dtype: object

Example:

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

import pandas as pd
import numpy as np

x = pd.Series(["Red", "Blue", "White", "Green", "Black"])

print("The Series contains:")
print(x)

#using negative indexing with the series
print("\nx.tail(-2) returns:")
print(x.tail(-2))

The output of the above code will be:

The Series contains:
0      Red
1     Blue
2    White
3    Green
4    Black
dtype: object

x.tail(-2) returns:
2    White
3    Green
4    Black
dtype: object

❮ Pandas Series - Functions