首页 > 解决方案 > 使用嵌套字典列表过滤数据框

问题描述

示例数据,我有一个数据框“df”:

ID 一个 b
1
2
3 W

有一个变量作为嵌套字典 filter_dict = [{'a': 'HH'}, {'a': 'W','b':'DOG'}] 的列表

如何使用循环直接通过其功能之一过滤数据框?

预期输出:

ID 一个 b
1
2
3 W

现在我想要另一个过滤器根据你们在合并时所做的相同逻辑排除,但现在 remove_dict = [{'a': 'HH', 'b':'CAT'}]

预期输出:

ID 一个 b
1
3 W

要求是我有一个巨大的数据框,我必须根据字典中的值(动态值和列)包含其中,然后根据另一个字典排除

标签: pythonpython-3.xpandasdataframe

解决方案


IIUC,您想从“过滤字典”创建一个数据框,然后pd.merge根据感兴趣的列来获取交集。要找到差异,您可以执行相同的操作,并使用该id列从原始数据框中删除相交的 id。

import pandas as pd


def filter_df(df, filter_dict, option='keep'):

    x = pd.concat([pd.merge(df, pd.DataFrame([dic]), 
                            how ='inner',
                            on=list(dic.keys()))
                   for dic in filter_dict], ignore_index=True).drop_duplicates()
    if option == "keep":
        return x
    elif option == "exclude":
        return df[df["id"].isin(x["id"].values) == False]
    else:
        NotImplementedError(f"Option {option} not implemented. Please choose between 'keep' and 'exclude'.")

以下是测试用例:

data = {"id": [1,2,3], "a": ["HH", "HH", "W"], "b": ["DOG", "CAT", "DOG"]}
df = pd.DataFrame(data)

# test case 1
filter_dict_1 = [{'a': 'HH'}, {'a': 'W','b':'DOG'}]
df1 = filter_df(df, filter_dict_1, "keep")
print(df1)
# #    id   a    b
# 0   1  HH  DOG
# 1   2  HH  CAT
# 2   3   W  DOG


# test case 2
filter_dict_2 = [{'a': 'HH', 'b': 'CAT'}]
df2 = filter_df(df, filter_dict_2, "exclude")
print(df2)
#   id   a    b
#0   1  HH  DOG
#2   3   W  DOG


# # test case 3
filter_dict_3 = [{'a': 'HH', 'b':'CAT'}, {"a": 'HH'}]
df3 = filter_df(df, filter_dict_3, "exclude")
print(df3)
#   id  a    b
#2   3  W  DOG

推荐阅读