Select Rows by Index List in Pandas

This tutorial will discuss about different ways to select rows by index list in pandas.

Table Of Contents

Preparing DataSet

First of all, we will create a DataFrame with some hardcoded values.

import pandas as pd

data = {'Col_A': [21, 12, 13, 14, 15, 16, 17],
        'Col_B': [21, 22, 23, 24, 25, 26, 27],
        'Col_C': [31, 32, 33, 34, 35, 36, 37]}

index=["D1", "D2", "D3", "D4", "D5", "D6", "D7"]

# Create DataFrame from dictionary
df = pd.DataFrame.from_dict(data)

# Set list index as Index of DataFrame
df .set_index(pd.Index(index), inplace=True)

print (df)

Output

    Col_A  Col_B  Col_C
D1     21     21     31
D2     12     22     32
D3     13     23     33
D4     14     24     34
D5     15     25     35
D6     16     26     36
D7     17     27     37

Now we will select rows from this DataFrame by a list of Indices.

Select DataFrame Rows by List of Index Labels/Names

If you want to select specific rows from a DataFrame based on the list of index labels or names. Then you can pass that list into the loc[] attribute of the DataFrame and it will return a DataFrame containing rows with the given Index Names, from the original DataFrame.

Like in the below example, we are going to select rows from the DataFrame, with Index Names D1, D3 or D6.

# List of index labels
labelList = ["D3", "D1", "D6"]

# Select DataFrame rows at the given index labels
subDf = df.loc[labelList]

print(subDf)

Output

    Col_A  Col_B  Col_C
D3     13     23     33
D1     21     21     31
D6     16     26     36

Select DataFrame Rows by List of Index Positions or Numbers

If you want to select rows from a DataFrame based on list of index positions or numbers, then you can pass this list of index numbers into the iloc[] attribute of the DataFrame. It will return a DataFrame containing rows at the given index numbers in original DataFrame.

In the below example, we are going to select DataFrame rows at index number 23 and 5.

# list of row index numbers/positions
indexList = [2, 3, 5]

# Select DataFrame rows at the given indices (numbers)
subDf = df.iloc[indexList]

print (subDf)

Output

    Col_A  Col_B  Col_C
D3     13     23     33
D4     14     24     34
D6     16     26     36

Summary

We learned how to select DataFrame rows by a list of Index Labels/Names or a list of Index Numbers. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top