I’m not sure how the matching is done here. It looks like with the current setup the target will be what is specified by index but image will simply be the last image assigned (which in this case is the last filename in files). I think there needs to be some correspondence used between index and the file. If you know the filename from the target image_id, can you just use that to open the correct image rather than iterating through all of them? It might be easier to understand if we see an example of the filename file as well as all of the data contained in a single row of the dataframe.
Finally, I don’t even see where files is defined; is it a global variable somewhere? I would guess that unless it is being mutated somewhere the exact same image would be returned every time with the current code.