Home > Enterprise >  How to select and insert value from another DataFrame by id?
How to select and insert value from another DataFrame by id?

Time:06-19

For example, I have two DataFrames:

a = [{'id':123, 'name': 'AAA'}, {'id':456, 'name': 'BBB'}, {'id':789, 'name': 'TTT'}]
df1 = pd.DataFrame(a)
print(df1)

b = [{'id':123}]
df2 = pd.DataFrame(b)
print(df2)

I need to add the new column in DataFrame df2['name']and to add the value from DataFrame df1['name'] by id. Something like df2['name'] = [df1['name'] where df2['id'] == df1['id']]. Yes i can use pd.merge but i want to do it try using this logic.

The option like where df1['id'] = 123 is not considered, because there should be a comparison of id dataframes.

Thanks.

CodePudding user response:

An alternative to DataFrame.merge is using DataFrame.set_index Series.map

df2['name'] = df2['id'].map(df1.set_index('id')['name'])

Output:

>>> df2

    id name
0  123  AAA

Setup:

import pandas as pd

a = [{'id':123, 'name': 'AAA'}, {'id':456, 'name': 'BBB'}, {'id':789, 'name': 'TTT'}]
df1 = pd.DataFrame(a)
b = [{'id':123}]
df2 = pd.DataFrame(b)
  • Related