【问题标题】:Generate column of unique ID in pandas在熊猫中生成唯一ID列
【发布时间】:2019-03-14 12:13:41
【问题描述】:

我有一个包含三列的数据框,bins_xbins_yz。我希望添加一个新列unique,它是bins_xbins_y 的独特组合的排序“索引”。以下是我想附加的示例。

请注意,为了清楚起见,我对数据框进行了排序,但在这种情况下,顺序并不重要。

import numpy as np
import pandas as pd
np.random.seed(12)
n = 1000
height = 20
width = 20
bins_x = np.random.randint(1, width, size=n)
bins_y = np.random.randint(1, height, size=n)
z = np.random.randint(1, 500, size=n)

df = pd.DataFrame({'bins_x': bins_x, 'bins_y': bins_y, 'z': z})
print(df.sort_values(['bins_x', 'bins_y'])



     bins_x  bins_y    z   unique
23        0       0  462   0
531       0       0  199   1
665       0       0  176   2
363       0       1  219   0
468       0       1  450   1
593       0       1  385   2
609       0       1   74   3
663       0       1   46   4
14        0       2  242   0
208       0       2  381   1
600       0       2  445   2
865       0       2  221   3
400       0       3  178   0
75        0       4  281   0
140       0       4  205   1
282       0       4   47   2
838       0       4  212   3

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用groupbycumcount

    df['unique'] = df.groupby(['bins_x','bins_y']).cumcount()
    
    >>> df.sort_values(['bins_x', 'bins_y']).head(10)
         bins_x  bins_y    z  unique
    207       1       1    4       0
    259       1       1  313       1
    327       1       1  300       2
    341       1       1   64       3
    440       1       1  398       4
    573       1       1   96       5
    174       1       2  219       0
    563       1       2  398       1
    796       1       2  417       2
    809       1       2  167       3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 2021-08-12
      • 1970-01-01
      • 2012-03-21
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多