Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

What are head and tail functions in pandas?

Hassaan Waqar

The pandas library in Python is used to work with dataframes which structures data in rows and columns. It is widely used in data analysis and machine learning.

Head function

The head function in Python displays the first five rows of the dataframe by default. It takes in a single parameter: the number of rows. We can use this parameter to display the number of rows of our choice.

Syntax

The head function is defined as follows:

dataframe.head(N)

N refers to the number of rows. If no parameter is passed, the first five rows are returned.

The head function also supports negative values of N. In that case, all rows except the last N rows are returned.

Example

The code snippet below shows how the head function is used in pandas:

import pandas as pd

# Creating a dataframe
df = pd.DataFrame({'Sports': ['Football', 'Cricket', 'Baseball', 'Basketball',
                'Tennis', 'Table-tennis', 'Archery', 'Swimming', 'Boxing']})

print(df.head()) # By default
print('\n')
print(df.head(3)) # Printing first 3 rows
print('\n')
print(df.head(-2)) # Printing all except the last 2 rows

Tail function

The tail function in Python displays the last five rows of the dataframe by default. It takes in a single parameter: the number of rows. We can use this parameter to display the number of rows of our choice.

Syntax

The tail function is defined as follows:

dataframe.tail(N)

N refers to the number of rows. If no parameter is passed, the first last rows are returned.

The tail function also supports negative values of N. In that case, all rows except the first N rows are returned.

Example

The code snippet below shows how the tail function is used in pandas:

import pandas as pd

# Creating a dataframe
df = pd.DataFrame({'Sports': ['Football', 'Cricket', 'Baseball', 'Basketball',
                'Tennis', 'Table-tennis', 'Archery', 'Swimming', 'Boxing']})

print(df.tail()) # By default
print('\n')
print(df.tail(3)) # Printing last 3 rows
print('\n')
print(df.tail(-2)) # Printing all except the first 2 rows

Summary

The illustration below summarizes head and tail functions in pandas:

How do head and tail functions work

RELATED TAGS

pandas
python

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring