【发布时间】: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