简体   繁体   English

如何遍历 Python 中的 Excel 电子表格行?

[英]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.我编写了一个脚本,根据图像的 x/y/r 像素坐标在图像特征周围绘制矩形,这一切都运行良好。 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]' ).但是,这是针对数据的第一行 ( '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.....如何调整此代码以自动迭代或循环遍历电子表格 (xeno_data) 的每一行,即“fandc 1 ”、“fandc[2]”、“fandc[3]”等......

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:在无法访问相同数据的情况下,您最初基于 fandc[0] 绘图,并希望遍历所有其他矩形 fandc[1]、fandc[2] 等。然后您可以尝试:

    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.看看我们如何用迭代索引 i 替换初始索引 0。

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.如果你正在努力让 for 循环工作,那么做一个关于它们的在线教程并用更简单的代码练习它们可能是明智的。 See https://www.w3schools.com/python/python_for_loops.asp for more info有关更多信息,请参阅https://www.w3schools.com/python/python_for_loops.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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