Pandas slice dataframe by multiple index ranges

Given a pandas dataframe, we have to slice it by multiple index ranges. By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given a DataFrame with multiple columns, we need to find a way to select some piece of data within several ranges of an index.

Slicing a pandas dataframe by multiple index ranges

We will take advantage of pandas.DataFrame.isin() method, first, we will create a DataFrame, and we will create two lists of different ranges and concatenate them. Finally, we will filter out data by accessing those indices which are present in the concatenated list.
This filtering is done with the help of pandas.DataFrame.isin() method which will only return the values which are present in the list.

Let us understand with the help of an example,

Python program to slice dataframe by multiple index ranges

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dictionary
d = {'a':range(10,100)}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original Dataframe :\n",df,"\n")

# Creating two lists
lists = [i for i in range(10,12)] + [i for i in range(25,28)]

# Selecting df by multiple index range
res = df[df.index.isin(lists)]

# Display result


The output of the above program is:

Example: Pandas slice dataframe by multiple index ranges

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.