Python,Pandas:如何检查一行是否包含在另一行中找到的值?

Python,Pandas:如何检查一行是否包含在另一行中找到的值?,python,pandas,Python,Pandas,我想得到一个将id 1和id 2标识为重复项的输出。因为id:2有值1,该值也可以在包含值1和2的id 2中找到。也就是说,id 2是1的子集 我尝试使用duplicate函数,但它没有将ID 1和2标识为重复项 #check by id if value is a duplicate test_df = pd.DataFrame({'id':['1', '2', '3', '4'], 'value':['1, 2', '1', '18', '19']})

我想得到一个将id 1和id 2标识为重复项的输出。因为id:2有值1,该值也可以在包含值1和2的id 2中找到。也就是说,id 2是1的子集

我尝试使用duplicate函数,但它没有将ID 1和2标识为重复项

#check by id if value is a duplicate
test_df = pd.DataFrame({'id':['1', '2', '3', '4'],
                   'value':['1, 2', '1', '18', '19']}) 

print(test_df)
duplicateRowsDF = test_df['value'].duplicated() #returns boolean values
duplicateRowsDF
这应该是反映的布尔值

重复行SDF 0对 1正确 2错误 3错误 名称:value,数据类型:bool

预期输出表如下所示

expected_output = pd.DataFrame({'id':['1', '2', '3', '4'],
                   'value':['1, 2', '1', '18', '19'], 'duplicate':['Yes', 'Yes', 'No', 'No']}) 
expected_output
用于熊猫0.25+:

#split by , and create Series with index by id column
s = test_df.set_index('id')['value'].str.split(', ').explode()

#check duplicates and get Trues per id if exist at least one, last convert to dict
d = s.duplicated(keep=False).groupby(level=0).transform('any').to_dict()
print (d)
{'1': True, '2': True, '3': False, '4': False}

#map id by dictionary and set values by mask
test_df['duplicate'] = np.where(test_df['id'].map(d), 'yes','no')
print (test_df)
  id value duplicate
0  1  1, 2       yes
1  2     1       yes
2  3    18        no
3  4    19        no

谢谢你,耶斯雷尔!我去试试看。你是一个救命的家伙,我看到你的名字超过了我在寻找的问题的答案everywhere@Bobby-是的,我回答了几年,所以这是可能的;)