使用python将simlar产品标记在一起

2024-09-30 18:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

基于3个键/列uniqueid、uniqueid2和uniqueid3,我需要生成一个列new_键,该键将用一个键标记所有关联行

对于标记相同的产品,我们需要在dataset中迭代比较所有3列。例如,当第一行与所有其他行进行比较时,基于任何列都没有相似性。但对于第二行,如果我们将其与第三行进行比较,它具有相同的uniqueid/uniqueid2。因此,它们被标记为起始行的唯一ID。现在是第四排唯一的3场比赛。因此,它也被标记在一起。所以,我们需要比较每一行

  df = pd.DataFrame({'uniqueid': {0: 'a', 1: 'b', 2: 'b', 3: 'c', 
                                   4: 'd', 5: 'd', 6: 'e', 7: 'e',8:'g',9:'g',10:'h',11:'l',12:'m'},
'uniqueid2': {0: 'a', 1: 'b', 2: 'b', 3: 'c', 
                                   4: 'd', 5: 'd', 6: 'e', 7: 'e',8:'g',9:'g',10:'h',11:'l',12:'l'},
                      'uniqueid3': {0: 'z', 1: 'y', 2: 'x', 3: 'y', 
                                    4: 'x', 5: 'v', 6: 'x', 7: 'u',8:'h',9:'i',10:'k',11:'k',12:'n'}})

基于uniqueid、uniqueid2和uniqueid3列的数据。我需要创建新的_键,因为它已经存在。在此虚拟数据中,根据第1列和第2列中的关联,除第一行之外的所有行都属于同一产品

但我不确定如何进一步进行。需要快速帮助吗

预期产量

enter image description here


Tags: 数据标记iddataframedfnew产品相似性
1条回答
网友
1楼 · 发布于 2024-09-30 18:34:31

因此,您希望构建一个dict并具有两个嵌套循环,每行,然后是每个键:set_值

# build a dictionary that contains the new keys and the unique values it refers to
# initialize with the first row
# and use numbers for keys, so we can +=1 later on
newkeys = {1: set(df.iloc[0].values)}
key_col = []
nextkey = 2

# loop df rows without the index
for row in df.itertuples(index=False):
    # and get unique row values
    rowset = set(row)

    # see if the row can be tagged with an existing newkey
    for key, values in newkeys.items():
        # if there is a value that appears in a previous row then the intersection will not be empty
       if rowset & values:
            # exit the for loop and skip the else clause
            # current newkey will be selected for the row
            break

    else:
        # for loop exhausted without breaking
        # none of  rowset values appear in any previous key
        # then create a new key
        key = nextkey
        nextkey += 1

    # add values to the newkey and tag row
    newkeys[key].update(rowset)
    key_col.append(key)

# save to df
df['new_key'] = key_col

相关问题 更多 >