根据应用于某一列的特定条件,从数据框架中删除行。
在这篇文章中,我们将讨论如何根据应用于某一列的特定条件从数据框架中删除记录的几种方法。保留所有那些在给定列上的应用条件评估为 “真 “的行。
我们之前已经讨论过如何根据标签来删除行或列。然而,在这篇文章中,我们将讨论如何根据应用于某一列的特定条件从数据框架中删除行的几种方法。保留所有那些在给定列上的应用条件评估为 “真 “的行。
创建Dataframe来删除行
在这个数据框架中,目前,我们有458行和9列。
# importing pandas as pd
import pandas as pd
# Read the csv file and construct the
# dataframe
df = pd.read_csv('nba.csv')
# Visualize the dataframe
print(df.head(15)
# Print the shape of the dataframe
print(df.shape)
输出:
根据某列的条件删除行
我们将使用矢量化操作从数据集中过滤出满足应用条件的这些行。让我们使用矢量化操作来过滤出所有满足给定条件的记录。
# Filter all rows for which the player's
# age is greater than or equal to 25
df_filtered = df[df['Age'] >= 25]
# Print the new dataframe
print(df_filtered.head(15)
# Print the shape of the dataframe
print(df_filtered.shape)
输出:
正如我们在输出中看到的,返回的Dataframe只包含那些年龄大于或等于25岁的球员。
根据一列上的多个条件删除行
正如我们在输出中看到的,返回的Dataframe只包含那些年龄不在20到25岁之间的球员,使用df.drop()。
# delete all rows with column 'Age' has value 30 to 40
indexAge = df[ (df['Age'] >= 20) & (df['Age'] <= 25) ].index
df.drop(indexAge , inplace=True)
df.head(15)
输出:
根据不同列上的多个条件删除行
在这里,我们用df.drop()删除所有名字和职位与 “John Holland “或 “SG “相关的记录。
# delete all rows with column 'Age' has value 30 to 40
indexAge = df[ (df['Name'] == 'John Holland') | (df['Position'] == 'SG') ].index
df.drop(indexAge , inplace=True)
df.head(15)
输出: