Pandas DataFrame.head
Pandas DataFrame.head
The DataFrame.head method in pandas is used to return the first n rows of a DataFrame. This method is particularly useful for quickly inspecting the top rows of a DataFrame and understanding its structure.
Syntax
The syntax for DataFrame.head is:
DataFrame.head(n=5)Here, DataFrame refers to the pandas DataFrame you want to inspect.
Parameters
| Parameter | Description |
|---|---|
n | An integer representing the number of rows to return. Defaults to 5. If n is larger than the number of rows in the DataFrame, all rows are returned. |
Returns
A DataFrame containing the first n rows.
Examples
Viewing the First Five Rows
By default, head returns the first 5 rows of a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya', 'Sita', 'Krishna'],
'Age': [25, 30, 35, 28, 40],
'Salary': [70000, 80000, 90000, 75000, 95000]
}
df = pd.DataFrame(data)
# View the first 5 rows
print("First 5 Rows:")
print(df.head())Output
First 5 Rows:
Name Age Salary
0 Arjun 25 70000
1 Ram 30 80000
2 Priya 35 90000
3 Sita 28 75000
4 Krishna 40 95000Viewing a Specific Number of Rows
Pass an integer to the n parameter to specify the number of rows to display.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya', 'Sita', 'Krishna', 'Laxman', 'Radha'],
'Age': [25, 30, 35, 28, 40, 27, 22],
'Salary': [70000, 80000, 90000, 75000, 95000, 72000, 68000]
}
df = pd.DataFrame(data)
# View the first 3 rows
print("First 3 Rows:")
print(df.head(3))Output
First 3 Rows:
Name Age Salary
0 Arjun 25 70000
1 Ram 30 80000
2 Priya 35 90000Viewing All Rows When n is Larger Than the DataFrame
If n is larger than the number of rows in the DataFrame, all rows are returned.
Python Program
import pandas as pd
# Create a small DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# View more rows than available
print("All Rows (n=10):")
print(df.head(10))Output
All Rows (n=10):
Name Age Salary
0 Arjun 25 70000
1 Ram 30 80000
2 Priya 35 90000Using head with an Empty DataFrame
If the DataFrame is empty, head returns an empty DataFrame.
Python Program
import pandas as pd
# Create an empty DataFrame
df_empty = pd.DataFrame()
# View the first 5 rows of an empty DataFrame
print("First 5 Rows of an Empty DataFrame:")
print(df_empty.head())Output
First 5 Rows of an Empty DataFrame:
Empty DataFrame
Columns: []
Index: []Summary
In this tutorial, we explored the DataFrame.head method in pandas. Key takeaways include:
- Using
headto quickly inspect the first few rows of a DataFrame. - Customizing the number of rows returned using the
nparameter. - Handling cases where
nexceeds the number of rows or when the DataFrame is empty.
The DataFrame.head method is a convenient tool for gaining insights into the structure and contents of a DataFrame.