Pandas DataFrame head() Method

The head() method in Pandas is used to return the first n rows of a DataFrame.

This method is beneficial to quickly glimpse a dataset’s beginning, especially when dealing with large DataFrames.

For negative values of n, this method returns all rows except the last n rows, equivalent to df[:-n].

This method is often combined with .info() or .describe() for a more comprehensive initial analysis.

Syntax

DataFrame.head(n=5) (n=5 is default we can set any value)

Parameters

Name Description
n Number of rows to select. The default is 5.

Return Value

It returns a DataFrame containing the first n rows.

Example 1: Default Usage (First 5 Rows)

Visual representation of Pandas DataFrame head() Method

import pandas as pd

df = pd.DataFrame({'A': range(1, 8), 'B': range(8, 15)})

print(df.head())

Output

Default usage of Pandas DataFrame head() method

Example 2: Specifying the number of rows

Figure of Specifying the number of rows

import pandas as pd

df = pd.DataFrame({'A': range(1, 8), 'B': range(8, 15)})

print(df.head(n = 3))

Output

Output of specifying the number of rows

You can use .head() to verify the changes after performing operations like sorting, filtering, or data manipulation.

Leave a Comment

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