我是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)
是否有一种方法可以在一个代码行中执行此操作,而不必为每个国家/地区执行一个操作?
答案 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)]