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
Answers:
Doing
mapper = dict(zip(list1,list2))
df['prod'] = df['prod'].map(mapper)
table["Product"] = table["Product"].apply(lambda p: list2[list1.index(p)])
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 |
Doing
mapper = dict(zip(list1,list2))
df['prod'] = df['prod'].map(mapper)
table["Product"] = table["Product"].apply(lambda p: list2[list1.index(p)])