【问题标题】:Groupby and assign unique IDs to group membersGroupby 并为组成员分配唯一 ID
【发布时间】:2020-01-18 10:19:44
【问题描述】:

我有一些数据框:

df = pd.DataFrame({'fruit': ['apple', 'apple', 'apple', 'apple', 'orange', 'orange', 'orange', 'orange', 'orange', 'orange'], 
                   'distance': [10, 0, 20, 40, 20, 50 ,70, 90, 110, 130]})
df

fruit   distance
0   apple   10
1   apple   0
2   apple   20
3   apple   40
4   orange  20
5   orange  50
6   orange  70
7   orange  90
8   orange  110
9   orange  130

我想为每个组成员添加一个按距离排序的唯一 ID,如下所示:

    fruit   distance    ID
0   apple   10  apple_2
1   apple   0   apple_1
2   apple   20  apple_3
3   apple   40  apple_4
4   orange  20  orange_1
5   orange  50  orange_2
6   orange  70  orange_3
7   orange  130 orange_6
8   orange  110 orange_5
9   orange  90  orange_4

我对 sort/groupby/loop 的努力还没有成功。

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    使用pandas.DataFrame.groupby.rank

    df['ID'] = df['fruit'] + "_" + df.groupby("fruit")["distance"].rank().astype(int).astype(str)
    print(df)
    

    输出:

        fruit  distance        ID
    0   apple        10   apple_2
    1   apple         0   apple_1
    2   apple        20   apple_3
    3   apple        40   apple_4
    4  orange        20  orange_1
    5  orange        50  orange_2
    6  orange        70  orange_3
    7  orange        90  orange_4
    8  orange       110  orange_5
    9  orange       130  orange_6
    

    【讨论】:

    • 我和你差不多。 df['id'] = (df['fruit'].str.cat(df.groupby('fruit')['distance'].rank().astype(int).astype(str),'_')) +1
    • 不错的解决方案!值得注意的是,对于相同距离的物品,默认的排序方法('average')并不能保证id的唯一性(也不是连续性),不像'first'方法那样更安全。
    • 没错,rank(method='first') 更安全,确保所有 ID 都是唯一的
    【解决方案2】:

    IIUC,

    sort 后跟 groupbycumsum 以及字符串连接。

    最后我不确定你的类型? - 但这应该可行。

    nums = (df.sort_values(["fruit", "distance"]).groupby(["fruit"]).cumcount() + 1).astype(str)
    
    df['ID'] = df['fruit'] + '_' + nums
    print(df)
            fruit  distance    ID
    0   apple        10   apple_2
    1   apple         0   apple_1
    2   apple        20   apple_3
    3   apple        40   apple_4
    4  orange        20  orange_1
    5  orange        50  orange_2
    6  orange        70  orange_3
    7  orange        90  orange_4
    8  orange       110  orange_5
    9  orange       130  orange_6
    

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 2014-06-03
      • 2018-10-05
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多