Home > Software design >  Python Pandas - Update column values based on two lists
Python Pandas - Update column values based on two lists

Time:10-06

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

CodePudding user response:

table["Product"] = table["Product"].apply(lambda p: list2[list1.index(p)])

CodePudding user response:

Doing

mapper = dict(zip(list1,list2))
df['prod'] = df['prod'].map(mapper)
  • Related