Python for Excel users · Lesson 7 of 14

VLOOKUP in Python with pandas

Do VLOOKUP, XLOOKUP, IFERROR and approximate-match lookups in pandas with map() and merge(), and avoid the duplicate-key trap.

About 17 minutes · code runs in your browser, nothing to install

You have an orders sheet with product codes and a price list on another sheet. In Excel you write =VLOOKUP(B2, Prices!A:C, 3, FALSE) and fill it down. pandas has two tools for this: map for one value and merge for several columns at once.

One value: map

Turn the price list into a lookup column with the code as row label (set_index), then map each order's code to it. This is a VLOOKUP with exact match.

Pythoneditable
import pandas as pd

orders = pd.DataFrame({
    "Order": [101, 102, 103, 104, 105],
    "Code": ["P2", "P1", "P3", "P9", "P2"],
    "Qty": [3, 1, 2, 5, 4],
})
prices = pd.DataFrame({
    "Code": ["P1", "P2", "P3"],
    "Name": ["Lamp", "Chair", "Desk"],
    "Price": [19.99, 45.0, 120.0],
})

price_of = prices.set_index("Code")["Price"]
orders["Price"] = orders["Code"].map(price_of)
print(orders)
Output
   Order Code  Qty   Price
0    101   P2    3   45.00
1    102   P1    1   19.99
2    103   P3    2  120.00
3    104   P9    5     NaN
4    105   P2    4   45.00

Code P9 is not in the price list, so its price is NaN, pandas' empty cell. Excel would show #N/A.

IFERROR and XLOOKUP's if_not_found

=IFERROR(VLOOKUP(…), 0) or =XLOOKUP(B2, Prices!A:A, Prices!C:C, 0) give a fallback when nothing is found. In pandas add .fillna(0).

Pythoneditable
import pandas as pd

orders = pd.DataFrame({
    "Order": [101, 102, 103, 104, 105],
    "Code": ["P2", "P1", "P3", "P9", "P2"],
    "Qty": [3, 1, 2, 5, 4],
})
prices = pd.DataFrame({
    "Code": ["P1", "P2", "P3"],
    "Name": ["Lamp", "Chair", "Desk"],
    "Price": [19.99, 45.0, 120.0],
})

price_of = prices.set_index("Code")["Price"]
orders["Price"] = orders["Code"].map(price_of).fillna(0)
orders["Total"] = orders["Qty"] * orders["Price"]
print(orders)
Output
   Order Code  Qty   Price   Total
0    101   P2    3   45.00  135.00
1    102   P1    1   19.99   19.99
2    103   P3    2  120.00  240.00
3    104   P9    5    0.00    0.00
4    105   P2    4   45.00  180.00

Several columns: merge

XLOOKUP can return several columns at once. merge joins two tables on a shared column and brings over every other column. how="left" keeps all the orders, like VLOOKUP does, even the ones without a match.

Pythoneditable
import pandas as pd

orders = pd.DataFrame({
    "Order": [101, 102, 103, 104, 105],
    "Code": ["P2", "P1", "P3", "P9", "P2"],
    "Qty": [3, 1, 2, 5, 4],
})
prices = pd.DataFrame({
    "Code": ["P1", "P2", "P3"],
    "Name": ["Lamp", "Chair", "Desk"],
    "Price": [19.99, 45.0, 120.0],
})

full = orders.merge(prices, on="Code", how="left")
print(full)
Output
   Order Code  Qty   Name   Price
0    101   P2    3  Chair   45.00
1    102   P1    1   Lamp   19.99
2    103   P3    2   Desk  120.00
3    104   P9    5    NaN     NaN
4    105   P2    4  Chair   45.00

how="inner" keeps only the rows found in both tables, which also tells you which orders have an unknown code. If the key columns have different names, write left_on="Code", right_on="SKU".

Pythoneditable
import pandas as pd

orders = pd.DataFrame({
    "Order": [101, 102, 103, 104, 105],
    "Code": ["P2", "P1", "P3", "P9", "P2"],
    "Qty": [3, 1, 2, 5, 4],
})
prices = pd.DataFrame({
    "Code": ["P1", "P2", "P3"],
    "Name": ["Lamp", "Chair", "Desk"],
    "Price": [19.99, 45.0, 120.0],
})

found = orders.merge(prices, on="Code", how="inner")
print(len(found), "of", len(orders), "orders matched")
missing = orders[~orders["Code"].isin(prices["Code"])]
print(missing)
Output
4 of 5 orders matched
   Order Code  Qty
3    104   P9    5

The ~isin line is a quick check for codes your lookup table does not know.

Watch out: VLOOKUP takes the first match when a code appears twice in the lookup table. merge returns one row per match, so a duplicated code doubles that order and your totals. Remove duplicates from the lookup table first with prices.drop_duplicates("Code"), and compare len() before and after the merge.

Approximate match: VLOOKUP with TRUE

=VLOOKUP(B2, Rates, 2, TRUE) finds the largest threshold that is not above the value, for tax brackets or discount tiers. pd.merge_asof does the same. Both tables must be sorted by the key.

Pythoneditable
import pandas as pd

tiers = pd.DataFrame({"Min": [0, 100, 500], "Discount": [0.0, 0.05, 0.1]})
orders = pd.DataFrame({"Order": [1, 2, 3, 4], "Min": [80, 640, 100, 250]})
orders = orders.sort_values("Min")
result = pd.merge_asof(orders, tiers, on="Min")
print(result.sort_values("Order"))
Output
   Order  Min  Discount
0      1   80      0.00
3      2  640      0.10
1      3  100      0.05
2      4  250      0.05

The order amount column is called Min here so that both tables share the key name; you could also use left_on and right_on.

✎ Exercise

Look up each employee's department name from depts using map. Employees with an unknown department code should get Unknown. Print the employees table.

Hint: depts.set_index("Dept")["DeptName"] is your lookup column; map it, then fillna("Unknown").

Your codewrite your answer, then Run
import pandas as pd

employees = pd.DataFrame({
    "Name": ["Ana", "Ben", "Chloe", "Dev"],
    "Dept": ["D1", "D3", "D2", "D7"],
})
depts = pd.DataFrame({
    "Dept": ["D1", "D2", "D3"],
    "DeptName": ["Sales", "Finance", "IT"],
})
# your code here

Expected output:

    Name Dept DeptName
0    Ana   D1    Sales
1    Ben   D3       IT
2  Chloe   D2  Finance
3    Dev   D7  Unknown
Show a solution
Solutioneditable
import pandas as pd

employees = pd.DataFrame({
    "Name": ["Ana", "Ben", "Chloe", "Dev"],
    "Dept": ["D1", "D3", "D2", "D7"],
})
depts = pd.DataFrame({
    "Dept": ["D1", "D2", "D3"],
    "DeptName": ["Sales", "Finance", "IT"],
})
name_of = depts.set_index("Dept")["DeptName"]
employees["DeptName"] = employees["Dept"].map(name_of).fillna("Unknown")
print(employees)
Output
    Name Dept DeptName
0    Ana   D1    Sales
1    Ben   D3       IT
2  Chloe   D2  Finance
3    Dev   D7  Unknown

Check yourself

1. Which merge option keeps every order, like VLOOKUP does?

2. What does pandas put where Excel's VLOOKUP shows #N/A?

3. Your lookup table has the same code twice. What happens with merge?

Spotted a mistake on this page? Tell us