Delete Pandas Rows by Condition: Guide

To delete rows based on specific conditions, you can use the drop method in conjunction with boolean indexing. Here is an example:

Suppose we have a DataFrame containing student information and we want to remove all students who are 18 years old or older.

import pandas as pd

# 创建示例DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [20, 17, 22, 19]}
df = pd.DataFrame(data)

# 显示原始DataFrame
print("原始DataFrame:")
print(df)

# 删除年龄大于等于18岁的行
df = df.drop(df[df['Age'] >= 18].index)

# 显示删除后的DataFrame
print("\n删除后的DataFrame:")
print(df)

Running the above code will output a DataFrame with rows where the age is greater than or equal to 18 removed. You can also modify it based on specific conditions.

bannerAds