我有一个像这样的数据框,其中一列包含国家/地区和其他列(与问题无关),如下所示。
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']
我现在想过滤国家/地区列并删除列表中的所有行(此处为国家/地区“AA”和“CC”,实际上还有更多)。
仅对于一个国家/地区,我会使用 df_new = df[df['country'].apply(lambda x: "AA" not in x)]
,效果很好 - 但我不知道如何迭代列表 to_drop = ['AA', 'CC']
包含我想要摆脱的国家/地区。
有人有我看不到的优雅解决方案吗?我已经检查了所有“过滤 Pandas ”问题,但没有成功。
最佳答案
我想出的唯一(不是很优雅的方式)是
for i in to_drop:
df_new = df[df['country'].apply(lambda x: i not in x)]
关于python - 根据列表过滤要删除的 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57356088/