Python 根据列表筛选要删除的数据帧
我有一个这样的数据框架,其中一列包含国家和其他列(与问题无关),如下所示Python 根据列表筛选要删除的数据帧,python,string,pandas,filter,Python,String,Pandas,Filter,我有一个这样的数据框架,其中一列包含国家和其他列(与问题无关),如下所示 data = {"country": ["AA", "BB", "AA", "CC", "DD", "AA", "BB", "AA", "CC", "DD"], "other variable": ["foo", "bar", "bla", "house", "fish", "car", "pet", "dog", "cat", "door"]} df = pd.DataFrame(data) to_drop = ['A
data = {"country": ["AA", "BB", "AA", "CC", "DD", "AA", "BB", "AA", "CC", "DD"],
"other variable": ["foo", "bar", "bla", "house", "fish", "car", "pet", "dog", "cat", "door"]}
df = pd.DataFrame(data)
to_drop = ['AA', 'CC']
我现在想过滤列country并删除列表中的所有行(这里是country“AA”和“CC”,实际上还有更多)
对于一个国家,我只会使用df_new=df[df['country'].apply(lambda x:“AA”not in x)]
,这很好——但我不知道如何迭代列表,以删除包含我想要摆脱的国家的['AA',CC']
有谁有我看不到的优雅解决方案吗?我已经检查了所有的“过滤熊猫”问题,但没有成功。我提出的唯一(不是很优雅的方式)是
for i in to_drop:
df_new = df[df['country'].apply(lambda x: i not in x)]
我测试了这个,它成功了
df_new=df[~df.country.isin(to_drop)]
df[~df.country.isin(to_drop)]有效!!你说有很多国家你必须放弃,不能在“放弃”中全部输入?@iamklaus,这个奇怪的方法对我不起作用。