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

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

我是一个自学成才的初学者“”“coder”””。对于我正在编写的更大的脚本,我需要编写一个函数来检查用户的输入是否存在于列(例如)A 的 excel 文件中,如果存在,则 return列中同一行的值(例如)B.

Screenshot of a sample excel file

在上图中,我会检查输入是否是 Seth 我会 return 500,如果是 John 我会 return 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 列中,这样您就可以在需要给定键的值时快速查找它们。 至少这对于小文件来说是个好主意。如果查找占用太多内存,您将不得不恢复扫描 excel 文件。

要使用字典,只需加载 excel table 并将感兴趣的两列整理到字典中。然后,您可以使用 try-except 块来检索值或输出错误消息。

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