What are head and tail functions in pandas?
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 dataframedf = pd.DataFrame({'Sports': ['Football', 'Cricket', 'Baseball', 'Basketball','Tennis', 'Table-tennis', 'Archery', 'Swimming', 'Boxing']})print(df.head()) # By defaultprint('\n')print(df.head(3)) # Printing first 3 rowsprint('\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 dataframedf = pd.DataFrame({'Sports': ['Football', 'Cricket', 'Baseball', 'Basketball','Tennis', 'Table-tennis', 'Archery', 'Swimming', 'Boxing']})print(df.tail()) # By defaultprint('\n')print(df.tail(3)) # Printing last 3 rowsprint('\n')print(df.tail(-2)) # Printing all except the first 2 rows
Summary
The illustration below summarizes head and tail functions in pandas:
Free Resources