慕标琳琳
我们可以通过以下方式实现。让我们首先创建一个虚拟数据框。import pandas as pdimport randominfo = { 'image_id': ['01', '01', '01', '02', '04', '04'], 'x':random.sample(range(500, 600), 6), 'y':random.sample(range(200, 500), 6), 'w':random.sample(range(200, 300), 6), 'h':random.sample(range(400, 600), 6), 'x_center':random.sample(range(250, 460), 6), 'y_center':random.sample(range(250, 460), 6), 'img_height':random.sample(range(2100, 3000), 6), 'img_width':random.sample(range(1100, 4000), 6), 'labels':[0,0,0,1,2,2]}df = pd.DataFrame(data=info)df.head()-------------------------- image_id x y w h x_center y_center img_height img_width labels0 01 561 435 290 449 303 318 2105 2806 01 01 583 447 265 427 394 421 2338 2047 02 01 520 417 262 592 429 395 2947 3388 03 02 516 415 214 470 455 319 2649 1594 14 04 522 386 204 514 343 394 2847 1770 2接下来,我们将获取groupyby图像ID并迭代每一行。df_image_id = df.groupby('image_id') # group by idfor _ , row in df_image_id: for _ , each in row.iterrows(): # iterate each samples within same id img_w = each['img_width'] img_h = each['img_height'] content = [ each['labels'], each['x_center']/each['img_width'], each['y_center']/each['img_height'], each['w']/each['img_width'], each['h']/each['img_height'] ] id = each['image_id'] with open(f'{id}.txt', 'a') as f1: f1.write(" ".join(str(x) for x in content)+ '\n')