In this article we will discuss how to select top or bottom N number of rows in a Dataframe using head() & tail() functions.


Select first N Rows from a Dataframe using head() function

pandas.DataFrame.head()

In Python’s Pandas module, the Dataframe class provides a head() function to fetch top rows from a Dataframe i.e.

It returns the first n rows from a dataframe. If n is not provided then default value is 5.
Let’s see how to use this.

Suppose we have a dataframe i.e.

Contents of the Dataframe :

Select top 5 rows from the dataframe

Output:

As we didn’t provide the argument n, whose default value is 5. Therefore head() function returned first 5 lines of the dataframe.

Select top 2 rows from the dataframe

Output:

As n=2 therefore head() function returned first 2 lines of the dataframe.

Select first N rows from the dataframe with specific columns

Instead of selecting all the columns while fetching first 3 rows, we can select specific columns too i.e.

Output:

It will return the top 3 values of given columns only.

Select last N Rows from a Dataframe using tail() function

pandas.DataFrame.tail()

In Python’s Pandas module, the Dataframe class provides a tail() function to fetch bottom rows from a Dataframe i.e.

It returns the last n rows from a dataframe. If n is not provided then default value is 5.
Let’s see how to use this.

Suppose we have a dataframe i.e.

Contents of the Dataframe :

Select bottom 5 rows from the dataframe

Output:

As we didn’t provide the argument n, whose default value is 5. Therefore tail() function returned last 5 lines of the dataframe.

Select bottom 2 rows from the dataframe

Output:

As n=2 therefore tail() function returned last 2 lines of the dataframe.

Select bottom N rows from the dataframe with specific columns

Instead of selecting all the columns while fetching last 3 rows, we can select specific columns too i.e.

Output:

It returns the bottom 2 values of given columns only.

Complete example is as follows,

Output:

Click Here to Subscribe for more Articles / Tutorials like this.