在Pandas上,如何基于一列删除多行

时间:2019-05-27 20:47:38

标签: python pandas

我是Pandas的新手,我正尝试从country列中删除包含相应国家(阿尔巴尼亚,乌兹别克斯坦,巴西)的所有行。但是,我想出的方法是一个接一个地完成,如下所示:

indexCountry = df[df['country'] == 'Albania'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Uzbekistan'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Brazil'].index
df.drop(indexCountry, inplace = True)

是否有一种方法可以在一个代码行中执行此操作,而不必为每个国家/地区执行一个操作?

3 个答案:

答案 0 :(得分:1)

您可以像这样进行过滤:

df = df[~df["country"].isin(["Alabania", "Uzbekistan", "Brazil"])]

~是其后跟否定项。

答案 1 :(得分:1)

您还可以使用此:

df = df[~df.country.str.contains('|'.join(["Albania","Uzbekistan","Brazil"]))]

答案 2 :(得分:0)

尝试:

list_of_countries = ['Albania',  'Uzbekistan', 'Brazil']
indexCountry = df[df['country'].isin(list_of_countries)].index 
df.drop(indexCountry, inplace = True)

or just:
list_of_countries = ['Albania',  'Uzbekistan', 'Brazil']
df[~df["country"].isin(list_of_countries)]
相关问题