Split pandas DataFrame Rows at Index Position in Python (Example Code)

In this article, I’ll demonstrate how to divide a pandas DataFrame at a particular row index position in the Python programming language.

Preparing the Example

import pandas as pd                       # Import pandas library to Python
my_df = pd.DataFrame({'A':range(1, 8),    # Construct pandas DataFrame
                      'B':['y', 'w', 'w', 'r', 's', 'w', 'y'],
                      'C':range(11, 18)})
print(my_df)
#    A  B   C
# 0  1  y  11
# 1  2  w  12
# 2  3  w  13
# 3  4  r  14
# 4  5  s  15
# 5  6  w  16
# 6  7  y  17

Example: Slicing pandas DataFrame Rows at Partocular Index Position

df_up = my_df.iloc[:4]                    # Extract rows above index
print(df_up)
#    A  B   C
# 0  1  y  11
# 1  2  w  12
# 2  3  w  13
# 3  4  r  14
df_low = my_df.iloc[4:]                   # Extract rows below index
print(df_low)
#    A  B   C
# 4  5  s  15
# 5  6  w  16
# 6  7  y  17

Further Resources & Related Tutorials

You may find some related Python tutorials below.

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