简体   繁体   中英

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.

Screenshot of a sample excel file

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.

I am finding xlrd and pandas docs very confusing. I am blocked between ifs and for loops. This is a mixture between the pseudocode and Python I am thinking of.

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. 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.

To use a dictionary, just load the excel table and collate the two columns of interest to a dictionary. Then, you can use a try-except block to retrieve the values or output an error message.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM