简体   繁体   English

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

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

I am a self-taught beginner “””coder”””.我是一个自学成才的初学者“”“编码器”””。 For a bigger script I am writing, I need to write a function that checks if the input of the user exists in an excel file in a column (say) A and, if it does, return the value of the same row in column (say) B.对于我正在编写的更大的脚本,我需要编写一个 function 检查用户的输入是否存在于列(例如)A 的 excel 文件中,如果存在,则返回列中同一行的值(说) B.

Screenshot of a sample excel file示例 excel 文件的屏幕截图

In the above picture, I would check if the input is Seth I will return 500, if it is John I will return 800, etcetera.在上图中,我会检查输入是否是 Seth 我将返回 500,如果是 John 我将返回 800,等等。

I am finding xlrd and pandas docs very confusing.我发现 xlrd 和 pandas 文档非常混乱。 I am blocked between ifs and for loops.我在 ifs 和 for 循环之间被阻塞了。 This is a mixture between the pseudocode and Python I am thinking of.这是我想到的伪代码和 Python 的混合体。

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

I imagine something like that but I cannot put it to work.我想象着类似的东西,但我无法将其付诸实践。 Thank you so much in advance!非常感谢您!

The best way to do this would be a lookup dictionary which stores all the values in Column A and their according values on Column B, so you can speedily look them up whenever you need the value for a given key.最好的方法是创建一个查找字典,它将所有值存储在 A 列中,并将它们的相应值存储在 B 列中,这样您就可以在需要给定键的值时快速查找它们。 At least this would be a good idea for small files.至少这对于小文件来说是个好主意。 If the lookup takes up too much memory, you would have to revert to scanning the excel file.如果查找占用太多 memory,您将不得不恢复扫描 excel 文件。

To use a dictionary, just load the excel table and collate the two columns of interest to a dictionary.要使用字典,只需加载 excel 表并将感兴趣的两列整理到字典中。 Then, you can use a try-except block to retrieve the values or output an error message.然后,您可以使用 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")

I did it with an excel file that resembles yours and got the answers:我用一个类似于你的文件的 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