如何根据多列创建唯一标识符?

eag*_*ent 7 python pandas

我有一个 pandas 数据框,看起来像这样:

    brand       description     former_price    discounted_price
0   A           icecream        1099.0          855.0   
1   A           cheese          469.0           375.0   
2   B           catfood         179.0           119.0   
3   C           NaN             699.0           399.0   
4   NaN         icecream        769.0           549.0
5   A           icecream        769.0           669.0   
Run Code Online (Sandbox Code Playgroud)

我想创建一个列,为每个品牌和描述组合分配唯一值。请注意,数据集中可能会缺少品牌或描述(由 NaN 值通知)。另请注意,如果品牌和描述相同(重复),我仍然希望该行的唯一值相同。

输出应如下所示:

    product_key   brand         description     former_price    discounted_price
0   1             A             icecream        1099.0          855.0   
1   2             A             cheese          469.0           375.0   
2   3             B             catfood         179.0           119.0   
3   4             C             NaN             699.0           399.0   
4   5             NaN           icecream        769.0           549.0
5   1             A             icecream        769.0           669.0   
Run Code Online (Sandbox Code Playgroud)

Product_key 中的值可以是任何值,我只是希望它们根据品牌和描述列是唯一的。非常感谢任何帮助!

多谢!

MrN*_*y33 9

你可以尝试pd.Series.factorize

df.set_index(['brand','description']).index.factorize()[0]+1
Run Code Online (Sandbox Code Playgroud)

输出:

0    1
1    2
2    3
3    4
4    5
5    1
Run Code Online (Sandbox Code Playgroud)

所以你可以尝试这个,将其指定为第一列:

df.insert(loc=0, column='product_key', value=df.set_index(['brand','description']).index.factorize()[0]+1)
Run Code Online (Sandbox Code Playgroud)

输出:

df
   product_key brand description  former_price  discounted_price
0            1     A    icecream        1099.0             855.0
1            2     A      cheese         469.0             375.0
2            3     B     catfood         179.0             119.0
3            4     C         NaN         699.0             399.0
4            5   NaN    icecream         769.0             549.0
5            1     A    icecream         769.0             669.0
Run Code Online (Sandbox Code Playgroud)