簡體   English   中英

如何遍歷 Python 中的 Excel 電子表格行?

[英]How to iterate through excel spreadsheet rows in Python?

我編寫了一個腳本,根據圖像的 x/y/r 像素坐標在圖像特征周圍繪制矩形,這一切都運行良好。 功能代碼如下:

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()

這段代碼產生了想要的結果,你可以從這個圖片 它已經成功地在圖像中心底部的一個特征上繪制了一個褪色的紅色矩形。

但是,這是針對數據的第一行 ( 'fandc[0]' ) 量身定制的。 如何調整此代碼以自動迭代或循環遍歷電子表格 (xeno_data) 的每一行,即“fandc 1 ”、“fandc[2]”、“fandc[3]”等......

謝謝大家!

在無法訪問相同數據的情況下,您最初基於 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))

看看我們如何用迭代索引 i 替換初始索引 0。

如果你正在努力讓 for 循環工作,那么做一個關於它們的在線教程並用更簡單的代碼練習它們可能是明智的。 有關更多信息,請參閱https://www.w3schools.com/python/python_for_loops.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM