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

问题描述 投票:1回答:1

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

数据帧:

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]}

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

预期产量:

{1: [11,22,33,555,], 2: [33, 88,99], 3:[11,88,99,222,555], 4: [33, 44], 5: [22, 33,44,55]}
python pandas
1个回答
2
投票

首先使用boolean indexingremoved值进行过滤,然后在dict comprehension中将值转换为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]}

编辑:

使用qazxsw poi的多个关键字过滤:

isin
© www.soinside.com 2019 - 2024. All rights reserved.