首页 > 解决方案 > 使用 python 将类似的产品标记在一起

问题描述

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

对于相同的产品标签,我们需要在数据集中迭代地比较所有 3 列。例如。与所有其他行相比,第一行没有基于任何列的相似性。但是对于第 2 行,如果我们将其与第 3 行进行比较,它具有相同的 uniqueid/uniqueid2。因此,它们被标记为起始行的唯一 ID。现在在第 4 行 Uniqueid3 匹配。所以,它也被标记在一起。所以,我们需要将每一行相互比较。

  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 的数据。我需要创建已经存在的 new_key 。在此虚拟数据中,除第一行之外的所有行都属于基于第 1 列和第 2 列中的关联的相同产品。

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

预期产出

在此处输入图像描述

标签: pythonpandas

解决方案


所以你想构建一个字典并有两个嵌套循环,每一行,然后是每个键:set_values。

# 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

推荐阅读