Retrieve elements from the head and tail of a Pandas Series

The head() and tail() instance methods of pandas Series class return new series objects containing the first and last 'n' elements from a pandas Series. The Python example sorts the series before retrieving the head and tail of a series instance.

Series Manipulations Updated 2 Nov 2019 1 min read

Overview

A pandas Series is designed to be loaded with huge amount of data such as time-series data. Often it is required to select a number of items from the beginning of the series or from the end of the series. The instance methods head() and tail() of the pandas Series returns first and last 'n' elements of a pandas Series object.

To manipulate a DataFrame in the same way, the head() and tail() methods of the DataFrame class can be used.

Example

python
# Example Python program to select the first

# first 'n' elements from a pandas Series

import pandas as pds

import numpy as np

# Generate 10 random integers

nums = np.random.randint(1, 10, 10);

# Create a series

s1 = pds.Series(nums);

print("Pandas Series:")

print(s1)

sorted = s1.sort_values();

print("Sorted series:")

print(sorted);

# Retrieve the first two elements from the sorted series

firstTwo = sorted.head(2);

# Retrieve the last two elements from the sorted series

lastTwo  = sorted.tail(2);

print("First two elements from the sorted series:");

print(firstTwo);

print("Last two elements from the sorted series:");

print(lastTwo);

Output

Output
Pandas Series:

0    7

1    9

2    3

3    1

4    8

5    9

6    1

7    1

8    5

9    8

dtype: int64

Sorted series:

3    1

6    1

7    1

2    3

8    5

0    7

4    8

9    8

1    9

5    9

dtype: int64

First two elements from the sorted series:

3    1

6    1

dtype: int64

Last two elements from the sorted series:

1    9

5    9

dtype: int64