Reputation: 538
I am working with pandas and my intention is to bring data from one table to other. Suppose I have two dataframes named df1 and df2:
df1 is like that:
Name Age Height
Marcus 18 170
Dan 21 172
Phill 30 165
Paty 24 160
Linda 25 158
df2 is like that:
Name Score1 Score2 Score3
Dan A C C
Paty B A B
Marcus C D B
Zoe A A B
I would like to find a way to pick the ages of the guys in df1 and bring it to df2, resulting in a table like that:
Name Score1 Score2 Score3 Age
Dan A C C 21
Paty B A B 24
Marcus C D B 18
Zoe A A B NaN
In Excel we use VLOOKUP function in df2 to df1. But I could not find something similar in Python.
Upvotes: 2
Views: 5696
Reputation: 38415
You can use map or merge, map would be faster
Option 1: Using map
df2['Age'] = df2['Name'].map(df1.set_index('Name')['Age'])
Option 2: Using merge
df2.merge(df1[['Name', 'Age']], 'left')
Either way you get
Name Score1 Score2 Score3 Age
0 Dan A C C 21.0
1 Paty B A B 24.0
2 Marcus C D B 18.0
3 Zoe A A B NaN
Upvotes: 8