python - 使用嵌套字典列表过滤数据框
问题描述
示例数据,我有一个数据框“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 | 狗 |
要求是我有一个巨大的数据框,我必须根据字典中的值(动态值和列)包含其中,然后根据另一个字典排除
解决方案
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
推荐阅读
- c# - 从另一个 DLL 引用一个 DLL - 缺少依赖项
- php - 在执行 LOAD DATA LOCAL INFILE 之前验证数据
- reactjs - React - 如何使用打字稿定义道具
- storybook - 在 Storybook 5.3 beta 中使用带有 HTML 元素的旋钮插件
- r - Rtools 是构建 R 软件包所必需的,但目前尚未安装
- python - 将无与 Python3 中的几个变量进行比较
- salesforce - Salesforce Oauth 错误。1814:身份验证期间发生意外错误
- tensorflow - NotFoundError:在 tensorflow 2.0 中生成随机整数数组时找不到节点的有效设备
- chat - 如何将音频通话添加到火箭聊天
- c++ - “std::decay_t (C++20 前)std::remove_cvref_t (C++20 起)”是什么意思?