How does the pandas.Series between() method work?


The between() method in pandas Series is used to check if the values of the series object lie in between the boundary values passed to the function. Or we can say that the between() method in the pandas series will check which data elements fall between the start and end value passed to the method.

It will return a series object with boolean values, it indicates True for particular elements if those elements lie in between the given range otherwise, it will indicate return False.

By default, the between() method includes the boundary values, if you want to change that we can use the inclusive parameter.

Example 1

import pandas as pd

# creating pandas Series with a list of integers
series = pd.Series([9,2,3,5,8,9,1,4,6])

print("Original Series object:",series)

# apply between method
print("Output: ",series.between(5,10))

Explanation

Here, we have created a pandas Series with a list of integers. Then we applied the between() method with 5,10 boundary values. The between() method will return a series object with boolean values.

Output

Original Series object:
0 9
1 2
2 3
3 5
4 8
5 9
6 1
7 4
8 6
dtype: int64

Output:
0  True
1 False
2 False
3  True
4  True
5  True
6 False
7 False
8  True
dtype: bool

As a result, it returns False for indices 1 to 3 and 6 to 7 because the values fall beyond the range 5 to 10. The remaining all are True.

Example 2

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.randint(1,100,10))

print("Original Series object:",series)

# apply between method
print("Output: ",series.between(10,50))

Explanation

In this example, we have created a series object using the pandas.series() function and NumPy.random.randint() function. This series object has 10 integer elements.

Then we applied the between method with 10,50 boundary values. By default these boundary values are inclusive.


Output

Original Series object:
0 21
1 92
2 66
3 36
4 24
5  4
6 53
7 62
8  9
9 11
dtype: int32

Output:
0  True
1 False
2 False
3  True
4  True
5 False
6 False
7 False
8 False
9  True
dtype: bool

We can see both the series objects, the first one is the original series object and the second one resultant series object. Here we got the boolean value “True” for values within the boundary, the remaining all elements are represented with False.

Updated on: 09-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements