How to Remove Rows of pandas DataFrame in Python (Example Code)

On this page, I’ll demonstrate how to drop rows of a pandas DataFrame in the Python programming language.

Setting up the Example

import pandas as pd                           # Import pandas library to Python
my_df = pd.DataFrame({"x1":range(10, 20),    # Constructing pandas DataFrame in Python
                      "x2":range(20, 10, - 1),
                      "x3":["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
                      "x4":[1, 1, 0, 1, 1, 1, 0, 0, 1, 0]})
print(my_df)                                 # Displaying pandas DataFrame
#    x1  x2 x3  x4
# 0  10  20  a   1
# 1  11  19  b   1
# 2  12  18  c   0
# 3  13  17  d   1
# 4  14  16  e   1
# 5  15  15  f   1
# 6  16  14  g   0
# 7  17  13  h   0
# 8  18  12  i   1
# 9  19  11  j   0

Example: Dropping Rows of pandas DataFrame Based On Logical Condition

my_df_new = my_df[my_df.x1 >= 15]            # Using logical condition
print(my_df_new)                             # Displaying new DataFrame
#    x1  x2 x3  x4
# 5  15  15  f   1
# 6  16  14  g   0
# 7  17  13  h   0
# 8  18  12  i   1
# 9  19  11  j   0

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