Pandas : Select first or last N rows in a Dataframe using head() & tail()

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.

DataFrame.head(self, n=5)

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.

# List of Tuples
empoyees = [('jack', 34, 'Sydney', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aadi', 16, 'Tokyo', 9) ,
           ('Sunil', 41,'Delhi' , 12) ,
           ('Veena', 33, 'Delhi' , 4) ,
           ('Shaunak',35,'Mumbai', 5 ),
           ('Shaun', 35, 'Colombo', 11)
            ]

# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

print("Contents of the Dataframe : ")
print(empDfObj)

Contents of the Dataframe :
Contents of the Dataframe : 
      Name  Age     City  Experience
a     jack   34   Sydney           5
b     Riti   31    Delhi           7
c     Aadi   16    Tokyo           9
d    Sunil   41    Delhi          12
e    Veena   33    Delhi           4
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11

Select top 5 rows from the dataframe
# Select the top 5 rows of the Dataframe
dfObj1 = empDfObj.head()

print("First 5 rows of the Dataframe : ")
print(dfObj1)

Output:
First 5 rows of the Dataframe : 
    Name  Age    City  Experience
a   jack   34  Sydney           5
b   Riti   31   Delhi           7
c   Aadi   16   Tokyo           9
d  Sunil   41   Delhi          12
e  Veena   33   Delhi           4

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

# Select the first 2 rows of the Dataframe
dfObj1 = empDfObj.head(2)

print("First 2 rows of the Dataframe : ")
print(dfObj1)

Output:
First 2 rows of the Dataframe : 
   Name  Age    City  Experience
a  jack   34  Sydney           5
b  Riti   31   Delhi           7

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

Advertisements

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.

# Select the top 3 rows of the Dataframe for 2 columns only
dfObj1 = empDfObj[['Name', 'City']].head(3)

print("First 3 rows of the Dataframe for 2 columns : ")
print(dfObj1)

Output:
First 3 rows of the Dataframe for 2 columns : 
   Name    City
a  jack  Sydney
b  Riti   Delhi
c  Aadi   Tokyo

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.

DataFrame.tail(self, n=5)

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.

# List of Tuples
empoyees = [('jack', 34, 'Sydney', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aadi', 16, 'Tokyo', 9) ,
           ('Sunil', 41,'Delhi' , 12) ,
           ('Veena', 33, 'Delhi' , 4) ,
           ('Shaunak',35,'Mumbai', 5 ),
           ('Shaun', 35, 'Colombo', 11)
            ]

# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

print("Contents of the Dataframe : ")
print(empDfObj)

Contents of the Dataframe :
Contents of the Dataframe : 
      Name  Age     City  Experience
a     jack   34   Sydney           5
b     Riti   31    Delhi           7
c     Aadi   16    Tokyo           9
d    Sunil   41    Delhi          12
e    Veena   33    Delhi           4
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11

Select bottom 5 rows from the dataframe
# Select the top 5 rows of the Dataframe
dfObj1 = empDfObj.head()

print("First 5 rows of the Dataframe : ")
print(dfObj1)

Output:
Last 5 rows of the Dataframe : 
      Name  Age     City  Experience
c     Aadi   16    Tokyo           9
d    Sunil   41    Delhi          12
e    Veena   33    Delhi           4
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11

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

# Select the bottom 2 rows of the Dataframe
dfObj1 = empDfObj.tail(2)

print("Last 2 rows of the Dataframe : ")
print(dfObj1)

Output:
Last 2 rows of the Dataframe : 
      Name  Age     City  Experience
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11

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.

# Select the bottom 3 rows of the Dataframe for 2 columns only
dfObj1 = empDfObj[['Name', 'City']].tail(3)

print("Last 3 rows of the Dataframe for 2 columns : ")
print(dfObj1)

Output:
Last 3 rows of the Dataframe for 2 columns : 
      Name     City
e    Veena    Delhi
f  Shaunak   Mumbai
g    Shaun  Colombo

It returns the bottom 2 values of given columns only.

Complete example is as follows,

import pandas as pd

def main():


    # List of Tuples
    empoyees = [('jack', 34, 'Sydney', 5) ,
               ('Riti', 31, 'Delhi' , 7) ,
               ('Aadi', 16, 'Tokyo', 9) ,
               ('Sunil', 41,'Delhi' , 12) ,
               ('Veena', 33, 'Delhi' , 4) ,
               ('Shaunak',35,'Mumbai', 5 ),
               ('Shaun', 35, 'Colombo', 11)
                ]

    # Create a DataFrame object
    empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

    print("Contents of the Dataframe : ")
    print(empDfObj)

    print('**** Select first n Rows from a Dataframe using head() function ****')

    # Select the top 5 rows of the Dataframe
    dfObj1 = empDfObj.head()

    print("First 5 rows of the Dataframe : ")
    print(dfObj1)

    # Select the first 2 rows of the Dataframe
    dfObj1 = empDfObj.head(2)

    print("First 2 rows of the Dataframe : ")
    print(dfObj1)

    # Select the top 3 rows of the Dataframe for 2 columns only
    dfObj1 = empDfObj[['Name', 'City']].head(3)

    print("First 3 rows of the Dataframe for 2 columns : ")
    print(dfObj1)

    print('**** Select last n Rows from a Dataframe using tail() function ****')

    # Select the bottom 5 rows of the Dataframe
    dfObj1 = empDfObj.tail()

    print("Last 5 rows of the Dataframe : ")
    print(dfObj1)

    # Select the bottom 2 rows of the Dataframe
    dfObj1 = empDfObj.tail(2)

    print("Last 2 rows of the Dataframe : ")
    print(dfObj1)

    # Select the bottom 3 rows of the Dataframe for 2 columns only
    dfObj1 = empDfObj[['Name', 'City']].tail(3)

    print("Last 3 rows of the Dataframe for 2 columns : ")
    print(dfObj1)


if __name__ == '__main__':
  main()

Output:
Contents of the Dataframe : 
      Name  Age     City  Experience
a     jack   34   Sydney           5
b     Riti   31    Delhi           7
c     Aadi   16    Tokyo           9
d    Sunil   41    Delhi          12
e    Veena   33    Delhi           4
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11
**** Select first n Rows from a Dataframe using head() function ****
First 5 rows of the Dataframe : 
    Name  Age    City  Experience
a   jack   34  Sydney           5
b   Riti   31   Delhi           7
c   Aadi   16   Tokyo           9
d  Sunil   41   Delhi          12
e  Veena   33   Delhi           4
First 2 rows of the Dataframe : 
   Name  Age    City  Experience
a  jack   34  Sydney           5
b  Riti   31   Delhi           7
First 3 rows of the Dataframe for 2 columns : 
   Name    City
a  jack  Sydney
b  Riti   Delhi
c  Aadi   Tokyo
**** Select last n Rows from a Dataframe using tail() function ****
Last 5 rows of the Dataframe : 
      Name  Age     City  Experience
c     Aadi   16    Tokyo           9
d    Sunil   41    Delhi          12
e    Veena   33    Delhi           4
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11
Last 2 rows of the Dataframe : 
      Name  Age     City  Experience
f  Shaunak   35   Mumbai           5
g    Shaun   35  Colombo          11
Last 3 rows of the Dataframe for 2 columns : 
      Name     City
e    Veena    Delhi
f  Shaunak   Mumbai
g    Shaun  Colombo

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top