繁体   English   中英

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

[英]On Pandas, how to drop multiple rows based in a column

我是Pandas的新手,我正尝试从Column 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)

有没有一种方法可以在一个代码行中做到这一点,而不必为每个国家/地区做一个?

您可以像这样进行过滤:

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

~是其后跟的否定。

尝试:

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)]

您还可以使用以下命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM