簡體   English   中英

如何使用 Python 遍歷 excel 中的列和行?

[英]How to iterate through columns and rows in excel with Python?

我是一個自學成才的初學者“”“編碼器”””。 對於我正在編寫的更大的腳本,我需要編寫一個 function 檢查用戶的輸入是否存在於列(例如)A 的 excel 文件中,如果存在,則返回列中同一行的值(說) B.

示例 excel 文件的屏幕截圖

在上圖中,我會檢查輸入是否是 Seth 我將返回 500,如果是 John 我將返回 800,等等。

我發現 xlrd 和 pandas 文檔非常混亂。 我在 ifs 和 for 循環之間被阻塞了。 這是我想到的偽代碼和 Python 的混合體。

listA = column A
listB = column B
for i in listA:
    if input in listA:
        return i.listB

我想象着類似的東西,但我無法將其付諸實踐。 非常感謝您!

最好的方法是創建一個查找字典,它將所有值存儲在 A 列中,並將它們的相應值存儲在 B 列中,這樣您就可以在需要給定鍵的值時快速查找它們。 至少這對於小文件來說是個好主意。 如果查找占用太多 memory,您將不得不恢復掃描 excel 文件。

要使用字典,只需加載 excel 表並將感興趣的兩列整理到字典中。 然后,您可以使用 try-except 塊來檢索值或 output 錯誤消息。

import pandas

data = pandas.read_excel("example.xlsx")
lookup = dict(zip(data["Names"],data["Values"]))

n = input("\nEnter the name: ")

try:
    print("The value is: "+str(lookup[n]))
except:
    print("There is no such name in the file")

我用一個類似於你的文件的 excel 文件做了它並得到了答案:

Enter the name: John
The value is: 800

Enter the name: Peter
The value is: 354

Enter the name: William
The value is: 132

Enter the name: Fritz
There is no such name in the file

Enter the name: Santa
There is no such name in the file

暫無
暫無

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

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