【问题标题】:assign indices in order of appearance [duplicate]按出现顺序分配索引[重复]
【发布时间】:2020-02-27 02:05:47
【问题描述】:

我有一个数据框

> df = pd.DataFrame({"user_hash": ["b","a","c", "a"]})
> df
  user_hash
0         b
1         a
2         c
3         a

其中user_hash 表示长散列值,因此为了清楚起见,我想添加一个列,该列仅按出现顺序枚举元素。在示例中,我想要的结果是:

> df2
  user_hash user_id
0         b       0
1         a       1
2         c       2
3         a       1

这个问题非常接近:Q: [Pandas] How to efficiently assign unique ID to individuals with multiple entries based on name in very large df,但由于它依赖于groupby,ids 的顺序是排序条目的自然顺序,而我希望 ids 按出现顺序排列。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用pd.factorize:

    labels, _ = pd.factorize(df['user_hash'])
    result = df.assign(user_id=labels)
    print(result)
    

    输出

      user_hash  user_id
    0         b        0
    1         a        1
    2         c        2
    3         a        1
    

    或者作为替代使用ngroup:

    result = df.assign(user_id=df.groupby('user_hash', sort=False).ngroup())
    print(result)
    

    输出

      user_hash  user_id
    0         b        0
    1         a        1
    2         c        2
    3         a        1
    

    【讨论】:

    • df.assign(user_id=df['user_hash'].factorize()[0]) 也可以。
    【解决方案2】:

    只需一条指令即可完成:

    df = df.merge(pd.DataFrame(df.user_hash.unique(), columns=['user_hash'])
        .reset_index(), how='left')
    

    结果是:

      user_hash  index
    0         b      0
    1         a      1
    2         c      2
    3         a      1
    

    如果需要,请将第二列名称 (index) 更改为您选择的任何其他名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 2019-05-27
      • 2012-05-24
      • 2014-11-13
      • 2020-04-17
      • 2018-07-25
      • 1970-01-01
      • 2016-06-12
      相关资源
      最近更新 更多