I have a CSV file which looks like:
Detection,Imagename,Frame_Identifier,TL_x,TL_y,BR_x,BR_y,detection_Confidence,Target_Length,Species,Confidence
0,201503.20150619.181140817.204628.jpg,0,272,142.375,382.5,340,0.475837,0,fish,0.475837
1,201503.20150619.181141498.204632.jpg,3,267.75,6.375,422.875,80.75,0.189145,0,fish,0.189145
2,201503.20150619.181141662.204633.jpg,4,820.25,78.625,973.25,382.5,0.615788,0,fish,0.615788
3,201503.20150619.181141662.204633.jpg,4,1257,75,1280,116,0.307278,0,fish,0.307278
4,201503.20150619.181141834.204634.jpg,5,194,281,233,336,0.586944,0,fish,0.586944
I load it as pandas.Dataframe named: imageannotation - I am interested in extracting a dictionary which has as key the imagename (note: Imagename can have duplicate rows), and as value, an other dictionary whit 2 keys: ['bbox',, 'species'], where bbox is a list given by the TL_x, TL_y, BR_x, BR_y values
I can accomplish this with the following code:
test = {
i: {
"bbox": imageannotation[imageannotation["Imagename"] == i][
["TL_x", "TL_y", "BR_x", "BR_y"]
].values,
"species": imageannotation[imageannotation["Imagename"] == i][
["Species"]
].values,
}
for i in imageannotation["Imagename"].unique()
}
The results looks like this:
mydict = {'201503.20150619.181140817.204628': {'bbox': array([[272. , 142.375, 382.5 , 340. ]]),
'species': array([['fish']], dtype=object)},
'201503.20150619.181141498.204632': {'bbox': array([[267.75 , 6.375, 422.875, 80.75 ]]),
'species': array([['fish']], dtype=object)},
'201503.20150619.181141662.204633': {'bbox': array([[ 820.25 , 78.625, 973.25 , 382.5 ],
[1257. , 75. , 1280. , 116. ]]),
'species': array([['fish'],
['fish']], dtype=object)},
'201503.20150619.181141834.204634': {'bbox': array([[194., 281., 233., 336.],
[766., 271., 789., 293.]]),
'species': array([['fish'],
['fish']], dtype=object)}}
which is what I wanted but can get extremely slow when working on large files.
Q: Do you have any better way to accomplish this?
My final target is to add a new column to a dataframe imagemetadata which is bigger than the has an Imagename field with unique values - and I do this last operation with:
for i in mydict:
imagemetadata.loc[imagemetadata.Imagename == i, "annotation"] = [test[I]]