Skip to content
Advertisement

Python Pandas – Update column values based on two lists

Suppose I have a table like this

Company_Name Product
A Apple
B Orange
C Pear
D Lemon

Given two lists
list1 = [‘Pear’, ‘Lemon’, ‘Apple’, ‘Orange’]
list2 = [1, 2, 3, 4]

How to replace Product name with the numerical values? The output should look like this –

Company_Name Product
A 3
B 4
C 1
D 2

Advertisement

Answer

table["Product"] = table["Product"].apply(lambda p: list2[list1.index(p)])
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement