The head()
method in Pandas is used to return the first n
rows of a pandas object, such as a Series or DataFrame. This method is especially useful when you quickly want to inspect the top rows of large datasets.
Example
import pandas as pd
# create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
'B': [5, 6, 7, 8, 9]}
df = pd.DataFrame(data)
# use head() to display the first 3 rows of the DataFrame
top_rows = df.head(3)
print(top_rows)
'''
Output
A B
0 1 5
1 2 6
2 3 7
'''
head() Syntax
The syntax of the head()
method in Pandas is:
obj.head(n=5)
head() Argument
The head()
method takes the following argument:
n
(optional) - specifies number of rows to return
head() Return Value
The head()
method returns a DataFrame or Series that contains the first n
rows of the original object.
Example 1: Display Default Number of Rows
import pandas as pd
# create a sample DataFrame
data = {'Values': [10, 20, 30, 40, 50, 60, 70]}
df = pd.DataFrame(data)
# use head() without any argument to get the default number of rows
top_rows = df.head()
print(top_rows)
Output
Values 0 10 1 20 2 30 3 40 4 50
In this example, we used the head()
method without any argument, so it returns the default number of rows, which is 5.
Example 2: Using head() on a Series
import pandas as pd
# create a sample Series
series_data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])
# display the top 4 elements of the Series
top_elements = series_data.head(4)
print(top_elements)
Output
0 1 1 2 2 3 3 4 dtype: int64
Here, we used the head()
method on a Series object to view its top 4 elements.