Extract Rows of pandas DataFrame by Indices in Python (Example Code)

This tutorial shows how to extract pandas DataFrame rows by indices in Python.

Creation of Example Data

import pandas as pd                                         # Load pandas
my_df = pd.DataFrame({'A':['x', 'y', 'x', 'y', 'x', 'y'],  # Construct example DataFrame
                      'B':['A', 'B', 'C', 'D', 'E', 'F'],
                      'C':['a', 'a', 'a', 'b', 'b', 'b']})
print(my_df)                                               # Display example DataFrame in console
#    A  B  C
# 0  x  A  a
# 1  y  B  a
# 2  x  C  a
# 3  y  D  b
# 4  x  E  b
# 5  y  F  b

Example: Select Certain Rows of pandas DataFrame by Index Position

print(my_df.iloc[[0, 3, 5]])
#    A  B  C
# 0  x  A  a
# 3  y  D  b
# 5  y  F  b

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top