Facebook Page Twitter Page LinkedIn Page
× Pandas Tutorial Pandas Resources


The Pandas Series - head() function returns the first n rows of the series. The syntax for using this function is given below:

Syntax

Series.head(n)

Parameters

n Required. Specify number of rows to select.

Return Value

Returns the first n rows of the series.

Example:

In the example below, the head() function returns first selected number of rows of the given series.

import pandas as pd
import numpy as np

x = pd.Series(["Red", "Blue", "White", "Green", "Black"])

#returning first two rows from series
print("x.head(2) returns:")
print(x.head(2))

#creating data frame
df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4, 3, 4],
  "Salary": [60, 62, 65, 59, 63, 62],
  "Name": ["John", "Marry", "Sam", "Jo", "Ramesh", "Kim"]}
)

print("\nThe DataFrame contains:")
print(df)

#returning first two rows from "Name" series/column
print("\ndf['Name'].head(2) returns:")
print(df["Name"].head(2))

The output of the above code will be:

x.head(2) returns:
0     Red
1    Blue
dtype: object

The DataFrame contains:
   Bonus    Name  Salary
0      5    John      60
1      3   Marry      62
2      2     Sam      65
3      4      Jo      59
4      3  Ramesh      63
5      4     Kim      62

df['Name'].head(2) returns:
0     John
1    Marry
Name: Name, dtype: object

Example:

n can take negative values as Python supports negative indexing. Consider the following example.

import pandas as pd
import numpy as np

x = pd.Series(["Red", "Blue", "White", "Green", "Black"])

print("The Series contains:")
print(x)

#using negative indexing with the series
print("\nx.head(-2) returns:")
print(x.head(-2))

The output of the above code will be:

The Series contains:
0      Red
1     Blue
2    White
3    Green
4    Black
dtype: object

x.head(-2) returns:
0      Red
1     Blue
2    White
dtype: object

❮ Pandas Series - Functions

5