简体   繁体   中英

How to iterate through excel spreadsheet rows in Python?

I have written a script that draws rectangles around features of an image according to their x/y/r pixel coordinates, and this is all functioning well. The functioning code is as follows:

ss = pd.read_excel(xeno_data)

fandc = []
for index, row in ss.head().iterrows():
   filename = row['filename']
   coords   = row['xyr_coords']
   # Use RegEx to find anything that looks like a group of digits, possibly seperated by decimal point.
   x, y, r = re.findall(r'[0-9.]+',coords)
   print(f'DEBUG: filename={filename}, x={x}, y={y}, r={r}')
   fandc.append({'filename': filename, 'x':x, 'y':y, 'r':r})

#Draw a transparent rectangle:
im = im.convert('RGBA')
overlay = Image.new('RGBA', im.size)
draw = ImageDraw.Draw(overlay)

#The x,y,r coordinates are centre of sponge (x,y) and radius (r).
draw.rectangle(((float(fandc[0]['x'])-float(fandc[0]['r']), float(fandc[0]['y'])-float(fandc[0]['r'])), (float(fandc[0]['x'])+float(fandc[0]['r']), float(fandc[0]['y'])+float(fandc[0]['r']))), fill=(255,0,0,55))

img = Image.alpha_composite(im, overlay)
img = img.convert("RGB")
# Remove alpha for saving in jpg format.

img.show()

This code produces the desired result, and you can see from这个图片 that it has succesfully drawn a faded red rectangle over a feature in the centre-bottom of the image.

However this is tailored to the first row of the data ( 'fandc[0]' ). How do I adjust this code to automatically iterate or loop through each row of my spreadsheet (xeno_data), ie 'fandc 1 ', 'fandc[2]', 'fandc[3]', etc, etc.....

Thanks all!

Without having access to the same data, you initially plot based on fandc[0] and want to go through all other rectangles fandc[1], fandc[2], etc. You could then try:

    for i in range(len(fandc)):
        draw.rectangle(((float(fandc[i]['x'])-float(fandc[i]['r']), float(fandc[i]['y'])-float(fandc[i]['r'])), (float(fandc[i]['x'])+float(fandc[i]['r']), float(fandc[i]['y'])+float(fandc[i]['r']))), fill=(255,0,0,55))

See how we replace our initial index 0 with our iterating index i.

If you are struggling getting for loops to work it is probably wise to do an online tutorial on them, and practicing them with simpler code. See https://www.w3schools.com/python/python_for_loops.asp for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM