Write a program in Python to print the elements in a series between a specific range

When working with Pandas Series, you often need to filter elements that fall within a specific range. Python provides several methods to accomplish this task efficiently.

Input − Assume, you have a series:

0    12
1    13
2    15
3    20
4    19
5    18
6    11

Output − The result for the elements between 10 to 15:

0    12
1    13
2    15
6    11

Using between() Method

The between() method is the most straightforward approach to filter elements within a range. It returns a boolean mask that can be used for indexing.

Example

import pandas as pd

values = [12, 13, 15, 20, 19, 18, 11]
data = pd.Series(values)

print("Original Series:")
print(data)
print("\nElements between 10 and 15:")
print(data[data.between(10, 15)])
Original Series:
0    12
1    13
2    15
3    20
4    19
5    18
6    11
dtype: int64

Elements between 10 and 15:
0    12
1    13
2    15
6    11
dtype: int64

Using Manual Filtering with isin()

This approach manually iterates through the series, collects matching values, and uses isin() to filter the original series.

Example

import pandas as pd

values = [12, 13, 15, 20, 19, 18, 11]
data = pd.Series(values)

# Create empty list to store matching values
filtered_values = []

# Iterate through series and collect values in range
for i in range(len(data)):
    if data[i] >= 10 and data[i] <= 15:
        filtered_values.append(data[i])

print("Filtered values:", filtered_values)
print("Series elements in range:")
print(data[data.isin(filtered_values)])
Filtered values: [12, 13, 15, 11]
Series elements in range:
0    12
1    13
2    15
6    11
dtype: int64

Using Boolean Indexing

You can also use direct boolean conditions to filter the series ?

import pandas as pd

values = [12, 13, 15, 20, 19, 18, 11]
data = pd.Series(values)

# Using boolean indexing
result = data[(data >= 10) & (data <= 15)]
print("Elements between 10 and 15:")
print(result)
Elements between 10 and 15:
0    12
1    13
2    15
6    11
dtype: int64

Comparison

Method Readability Performance Best For
between() High Fast Simple range filtering
Boolean indexing High Fast Complex conditions
isin() method Medium Slower Learning purposes

Conclusion

The between() method is the most efficient and readable approach for filtering series elements within a range. Use boolean indexing for more complex filtering conditions.

Updated on: 2026-03-25T15:49:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements