Pandas DataFrame head() method returns the first n rows of a DataFrame, allowing developers to inspect the top portion of the dataset quickly. It provides a quick snapshot.
In the above figure, we are fetching the first five rows by default.
Syntax
DataFrame.head(n=5)
Parameters
Name | Description |
n (optional, int) | It represents the number of rows to select.
The default is 5. It can be a positive or negative number, depending on your requirement. |
Default (First 5 Rows)
Let’s display the first five rows of the DataFrame, preserving columns and index.
import pandas as pd df = pd.DataFrame({ 'Name': ['Krunal', 'Tom', 'Niva', 'Vidisha', 'Harry', 'Maya', 'Bam', 'Chandani'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male', 'Female', 'Male', 'Female'] }) print(df.head())
You can see that it does not modify the row index and columns.
Custom number of rows
To control the number of rows, use the n parameter, which allows you to pass any number, and it will return the DataFrame with that number of rows.
Let’s fetch just the first two rows.
import pandas as pd df = pd.DataFrame({ 'Name': ['Krunal', 'Tom', 'Niva', 'Vidisha', 'Harry', 'Maya', 'Bam', 'Chandani'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male', 'Female', 'Male', 'Female'] }) print(df.head(2))
Negative n
When you pass a negative integer as an n parameter in df.head(n), it returns all rows except the last n rows of the DataFrame.
For example, if n = -3, it returns the DataFrame except the last three rows.
import pandas as pd df = pd.DataFrame({ 'Name': ['Krunal', 'Tom', 'Niva', 'Vidisha', 'Harry', 'Maya', 'Bam', 'Chandani'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male', 'Female', 'Male', 'Female'] }) print(df.head(-3))
n is larger than the DataFrame size
What if you pass a number of rows (n) that is larger than the DataFrame size? In other words, if the input DataFrame has a total of 8 rows and you pass the number of rows as 9. Well, in that case, it returns the whole DataFrame in the output.
import pandas as pd df = pd.DataFrame({ 'Name': ['Krunal', 'Tom', 'Niva', 'Vidisha', 'Harry', 'Maya', 'Bam', 'Chandani'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male', 'Female', 'Male', 'Female'] }) print(df.head(9))
Avoid using very large n values; prefer slicing for better control.
Empty DataFrame handling
In case of an empty DataFrame, you will get an empty DataFrame as a result.
import pandas as pd empty_df = pd.DataFrame() print(empty_df.head()) # Output: # Empty DataFrame # Columns: [] # Index: []
That’s all!