Pandas tail function

In this tutorial, we will learn how to use the tail function in pandas in Python. This function is used to return the last 5 rows of the data frame or the series.

This will help in the process of retrieving the data. So, let’s begin the tutorial.

Tail function

The syntax for the tail function is:

pandas.dataframe.tail() or dataframe.tail()

It has 2 parameters

n: It is used to specify the number of lines to be returned from the bottom.

Return: Directly returns the number of lines specified from the bottom.

Let’s create a data frame and demonstrate the above function.

By using the parameter n in pandas tail function

Here, we will choose the value of n as 2. Returns the last 2 lines from the data frame.

import pandas as p
data1 = { '0':[1,2,3,4,5], '1':['a','b','c','d','e'] }
h=2
d1 = p.DataFrame(data1).tail(n=h)
print(d1)

The code can also be written as:

import pandas as p
data1 = { '0':[1,2,3,4,5], '1':['a','b','c','d','e'] }
h=2
d1 = p.DataFrame(data1)
print(d1.tail(n=h))

OUTPUT:

  0 1
3 4 d
4 5 e

2)By using the return type

Here, we do not use n value

import pandas as p
data1 = { '0':[1,2,3,4,5], '1':['a','b','c','d','e'] }
d1 = p.DataFrame(data1).tail(2)
print(d1)

The code can also be written as:

import pandas as p
data1 = { '0':[1,2,3,4,5], '1':['a','b','c','d','e'] }
d1 = p.DataFrame(data1)
print(d1.tail(2))

OUTPUT:

  0 1
3 4 d
4 5 e

Negative values can also be passed as an argument

import pandas as p
data1 = { '0':[1,2,3,4,5], '1':['a','b','c','d','e'] }
d1 = p.DataFrame(data1)
print(d1.tail(-1))

OUTPUT:

  0 1
1 2 b
2 3 c
3 4 d
4 5 e

It displays all the rows except the first row.

Leave a Reply

Your email address will not be published.