根据lis过滤掉的数据帧

2024-04-20 02:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据框架,其中一列包含国家和其他列(与问题无关),如下所示。你知道吗

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)],这很好-但我不知道如何反复列出to_drop = ['AA', 'CC']包含我想要摆脱的国家。你知道吗

有人有我看不到的优雅解决方案吗?我检查了所有的“过滤熊猫”问题都没有成功。你知道吗


Tags: to数据框架dfdatafoo国家variable
2条回答

我测试过了这是有效的

df_new=df[~df.country.isin(to_drop)]

我唯一想到的(不是很优雅的方式)是

for i in to_drop:
    df_new = df[df['country'].apply(lambda x: i not in x)]

相关问题 更多 >