Add a cloumn of a Dataframe to another dataframe when there is a specific match

Viewed 93

I have a Dataframe called df1 that is as follows:

import pandas as pd

id_1 = [1,2,3,4,5,6,7]
df_1 = pd.DataFrame(zip(id_1, data_1), columns =['id', 'data'])

enter image description here

And now another Dataframe called df2:

id_2 = [1,3,5,7]
df_2 = pd.DataFrame(id_2, columns = ['id'])

enter image description here

What I want to know is how can I add the values of data from df1 into df2 whenever there is a match in id.

So basically the desired result would be:

enter image description here

4 Answers

Use map with dictionary:

dd = {k:v for k, v in zip(df_1['id'], df_1['data'])}
df_2['data'] = df_2['id'].map(dd)
df_2

Output:

   id  data
0   1   0.1
1   3   0.3
2   5   0.5
3   7   0.7

Timings:

enter image description here

You can do this way using map(),

df_2['data'] = df_2['id'].map(df_1.set_index('id')['data'])

here, mapping each id of df_2 based on df_1.set_index('id')['data'] series and setting the value using df_2['data']

Using merge,

 pd.merge(df_2,df_1, how='inner')

here, doing simple inner join both of df_1 and df_2

You can merge or join the dataframes:

df_2.merge(df_1, on='id')

Or

df_2.join(df_1.set_index('id') , on='id', how='inner')

Example:

>>> df_1 = pd.DataFrame(zip(id_1, data_1), columns =['id', 'data'])
   id  data
0   1   0.0
1   2   0.1
2   3   0.2
3   4   0.3
4   5   0.4
5   6   0.5
6   7   0.6

>>> df_2 = pd.DataFrame(id_2, columns = ['id'])
   id
0   1
1   3
2   5
3   7

>>> df_2.merge(df_1 , on='id', how='inner') #merging the dataframes
   id  data
0   1   0.0
1   3   0.2
2   5   0.4
3   7   0.6

>>> df_2.join(df_1.set_index('id') , on='id', how='inner')
   id  data
0   1   0.0
1   3   0.2
2   5   0.4
3   7   0.6

You can use the dataframes method merge to join your data:

df_2 = df_2.merge(df_1, how='left', on='id')
Related