Retrieve elements from the head and tail of a Pandas Series

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:

# 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:

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


Copyright 2024 © pythontic.com