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)
import pandas as pd
df = pd.DataFrame({'A': range(1, 8), 'B': range(8, 15)})
print(df.head())
Output
Example 2: 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
You can use .head() to verify the changes after performing operations like sorting, filtering, or data manipulation.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.