如果数据帧是:
id name nicknames
1 i-123 sg-123
1 i-123 sg-234
1 i-123 sg-345
2 i-456 sg-654
2 i-456 sg-765
2 i-789 sg-875
2 i-789 sg-123
2 i-789 sg-987
2 i-789 sg-765
列表为:
prob = ['sg-123','sg-234','sg-345','sg-456','sg-567','sg-678']
检查df['nicknames']是否在prob列表中,并根据上面的df生成下面的数据帧。
前3列的行应该减少,因为我们需要每个名称的昵称列表,就像预期的结果数据帧一样。第4列:如果昵称有问题,则将该列中的昵称打印为列表。第5列:如果昵称没有问题,则将该列中的昵称打印为列表。第6列:第4列的计数第7列:第5列的计数。预期结果数据帧:
id name nicknames exist not_exist count_exist count_not_exist
1 i-123 ['sg-123',' sg-234',' sg-345'] ['sg-123',' sg-234',' sg-345'] Null 3 0
2 i-456 ['sg-654','sg-765'] Null ['sg-654','sg-765'] 0 2
2 i-789 ['sg-875','sg-123','sg-987','sg-765'] ['sg-123'] ['sg-875','sg-987','sg-765'] 1 3
IIUC:
d = df.groupby(['id', 'name'], as_index=False).nicknames.agg(list)
e = d.nicknames.map(lambda x: [*{*x} & {*prob}])
n = d.nicknames.map(lambda x: [*{*x} - {*prob}])
d.assign(exist=e, not_exist=n, count_exist=e.str.len(), count_not_exist=n.str.len())
id name nicknames exist not_exist count_exist count_not_exist
0 1 i-123 [sg-123, sg-234, sg-345] [sg-234, sg-123, sg-345] [] 3 0
1 2 i-456 [sg-654, sg-765] [] [sg-654, sg-765] 0 2
2 2 i-789 [sg-875, sg-123, sg-987, sg-765] [sg-123] [sg-987, sg-875, sg-765] 1 3