簡體   English   中英

如何基於多列創建唯一標識符?

[英]How to create a unique identifier based on multiple columns?

我有一個 pandas dataframe 看起來像這樣:

    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   

我想創建一個列,為每個品牌和描述組合分配一個唯一值。 請注意,數據集中可能缺少品牌或描述(由 NaN 值通知)。 另外,請注意,如果品牌和描述相同(重復),我仍然希望行的唯一值相同。

output 應如下所示:

    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   

product_key 中的值可以是任何值,我只希望它們基於品牌和描述列是唯一的。 非常感謝任何幫助!

非常感謝!

您可以嘗試使用pd.Series.factorize

df.set_index(['brand','description']).index.factorize()[0]+1

Output:

0    1
1    2
2    3
3    4
4    5
5    1

所以你可以試試這個,把它分配給第一列:

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

Output:

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

groupby+ngroup

(df.fillna({'brand':'','description':''})
   .groupby(['brand','description'],sort=False).ngroup()+1)

0    1
1    2
2    3
3    4
4    5
5    1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM