[英]How to iterate through columns and rows in excel with Python?
我是一个自学成才的初学者“”“编码器”””。 对于我正在编写的更大的脚本,我需要编写一个 function 检查用户的输入是否存在于列(例如)A 的 excel 文件中,如果存在,则返回列中同一行的值(说) B.
在上图中,我会检查输入是否是 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.