【问题标题】:How to Assign value for unique values in Python如何在 Python 中为唯一值赋值
【发布时间】:2020-08-05 18:46:30
【问题描述】:

df:

Id     Products
100     Shoes
101     Shoes
102     Shoes
103     Chair
104     Chair
105     Chair
106     Chair
107     Chair
108     Clothes
109     Clothes
110     Clothes

df_输出:

Id     Products Value
100     Shoes    1
101     Shoes    1
102     Shoes    1
103     Chair    2
104     Chair    2
105     Chair    2
106     Chair    2
107     Chair    2
108     Clothes  3
109     Clothes  3
110     Clothes  3

我需要基于“产品”列创建一个新列,该列为每个不同的产品分配每个唯一值。

【问题讨论】:

    标签: python python-3.x pandas python-2.7


    【解决方案1】:

    使用factorize

    df['Value']=df.Products.factorize()[0]+1
    

    输出

    df
         Id Products  Value
    0   100    Shoes      1
    1   101    Shoes      1
    2   102    Shoes      1
    3   103    Chair      2
    4   104    Chair      2
    5   105    Chair      2
    6   106    Chair      2
    7   107    Chair      2
    8   108  Clothes      3
    9   109  Clothes      3
    10  110  Clothes      3
    

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2020-06-08
      • 2015-04-24
      • 2019-05-24
      • 2013-04-17
      相关资源
      最近更新 更多