我有一些DataFrame:
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的尝试尚未成功。
参考方案
使用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
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
python JSON对象必须是str,bytes或bytearray,而不是'dict - python在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…