gpt4 book ai didi

python - 使用数据框从字典中仅选择所需的键

转载 作者:行者123 更新时间:2023-12-01 02:05:23 25 4
gpt4 key购买 nike

我有一个包含产品及其状态的数据框,如下所示

数据框:

products    status
11 sale
22 sale
33 notsale
44 notsale
55 notsale
66 removed
77 removed
88 notsale
99 sale
222 sale
333 removed
444 removed
555 notsale

我还有一个用户数据作为字典,其中包含用户和他们感兴趣的产品列表。

{1: [11,22,33,555,33], 2:[33,66,77,88,99],3:[11,88,99,222,333,555],4:[333,33,444,44],5:[333,444,22,33,44,55,66]}

我需要做的是,删除状态为已删除的产品以及用户对上述字典感兴趣的重复项。

预期输出:

{1: [11,22,33,555,], 2: [33, 88,99], 3:[11,88,99,222,555], 4: [33, 44], 5: [22, 33,44,55]}

最佳答案

首先按boolean indexing过滤删除已删除的值,然后在字典理解中将值转换为set以获得唯一值,然后删除a的值:

a = df.loc[df['status'] == 'removed', 'products'].tolist()
print (a)
[66, 77, 333, 444]

d = {1: [11,22,33,555,33], 2:[33,66,77,88,99],
3:[11,88,99,222,333,555], 4:[333,33,444,44],5:[333,444,22,33,44,55,66]}

d1 = {k: list(set(v)-set(a)) for k, v in d.items()}
print (d1)
{1: [33, 11, 22, 555], 2: [88, 33, 99],
3: [11, 555, 99, 222, 88], 4: [33, 44], 5: [33, 44, 22, 55]}

编辑:

要按多个关键字进行过滤,请使用 isin :

a = df.loc[df['status'].isin(['removed', 'notsale']), 'products'].tolist()

关于python - 使用数据框从字典中仅选择所需的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com