python - Groupby 并为组成员分配唯一 ID

标签 python pandas pandas-groupby

我有一些数据帧:

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

我对排序/分组/循环的努力尚未成功。

最佳答案

使用 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

关于python - Groupby 并为组成员分配唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796922/

相关文章:

python - 在python中合并df

python - 按唯一 ID 分组、应用函数并更新下一组的特定列

python - 需要让我的 python web 应用程序像守护进程一样 self 监控(保持事件状态)

python - 从 np.array 保存到 JPG 时,cv2.imwrite 改变颜色

python - 在 Pandas 中将列拆分为列表

python-3.x - 如何根据日期时间约束从另一个数据帧中提取行?

python - Pandas 按 2 列分组,使用另一列查找增量

python - 将组内的行合并在一起

Python nltk 只读

python - 迭代包含字典中的键的列。从第二个字典返回匹配的键,保持第一个字典中键的顺序