Set dataframe value based on condition of another dataframe

Question:

Table 1:

ID Name Column C Column D
1234hj Bob 1 1
nkj234 Joe 2 2
ji3251 Schmoe 3 3

Table 2:

ID Name
Bob
Joe
Sam

I currently have 2 dataframes like so. How do i extract the ID from table 1 and set it as ID in table 2 IF the name matches?

I’ve tried this code but requires same labelling. (This may not even be correct)

df2['ID'] = np.where(df['Name'] == df2['Name'], 
                        df['Prompt'], df2['ID'])
Asked By: Janzen Liu

||

Answers:

You can try this:

df2['ID'] = df2['Name'].map(df.set_index('Name')['ID'])

pd.merge is also an option here.

Answered By: Rabinzel
table2 = pd.merge(table1[['ID','Name']], table2[['Name']], how='right', on='Name')
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.