[英]Python, Pandas: How to check if a row contains values found in another row?
我想获得一个将id 1和2标识为重复项的输出。 因为id:2的值是1,在id 2中也包含值1和2。即id 2是一个值的子集。
我尝试使用重复功能,但未将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
这应该是反映的布尔值
repeatRowsDF 0是1是2是3是否名称:value,dtype: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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.