Python Pandas – Update column values based on two lists

Question:

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
Asked By: Lychee

||

Answers:

Doing

mapper = dict(zip(list1,list2))
df['prod'] = df['prod'].map(mapper)
Answered By: BENY
table["Product"] = table["Product"].apply(lambda p: list2[list1.index(p)])
Answered By: Raibek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.