Search code examples
pythonflaskjinja2

Python Vlookup to return one value only - similar to excel


I'm trying to replicate an Excel Vlookup in Python, using Flask. I've an excel sheet, set out like this: (Item is column A, Price is column B).

Item:                     Price:
Keyboard                  £10
Mouse                     £5
Mousemat                  £5
Beer                      £4

Now in Excel, if I had want to know the Price of Mouse, and that was typed in on cell C1, I'd do:

=VLOOKUP(C1,A2:B5,2,FALSE)

That'd return me £5. This is exactly what I want to do, but in Python. I've read some tutorials online, that points me in the direction of Pandas and xlrd, but this appears to be merging two columns together. This isn't what I want. I want it to only display the result, as i've done in my excel example above This is because I want to display this result in a Jinja template. FYI, the value "Mouse" will be input by a user, and the list will be massive. Hence my involvement of an Excel spreadsheet.


Solution

  • Answered my own question using pandas. For those that may stumble across anything like this in the future, my solution was this:

    import pandas
    df = pd.read_excel('test.xlsx', sheet_name='Sheet1')
            price = df[df['Price'] == Mousemat]['Item'].sum()
    

    So this is how you'd do a Vlookup in Python, without using merge like every other example I found.