简体   繁体   中英

How can I join two dataframes together

My first data frame has various columns one of which contains ID column and my second data frame has various columns one of which contains a No so I have found the link between the two. However how can I link these together using the number to assign the postcode information from data frame 2 to the correct practice in data frame 1.

Any help would be greatly appreciated!!!

Date frame 1

ID  place  Items Cost
0      5     10  2001.00
1     12     2  20.98
2      2     4  100.80
3      7     7  199.60

Data frame 2

ID   No     Dr      Postcode
0      1     Dr.K     BT94 7HX
1      5     Dr.H     BT7 4MC
2      3     Dr.Love  BT9 1HE
3      7     Dr.Kerr  BT72 4TX

I want to create a new column 'Postcode' in Data frame 1 and assign the postcode to the correct Practice

ID  Place Items Cost Postcode      
0      5         10  BT7 4MC
1      2          3  BT9 1HE
2      22         8  BT62 4TU
3      7          7  BT72 4TX

How can I do this??

IIUC, I think what you are looking for is 'left_on' and 'right_on' parameters in merge:

df1.merge(df2, left_on='Practice', right_on='Prac No')

Output:

   ID_x  Practice  Items    Cost  ID_y  Prac No       Dr  Postcode
0     0         5     10  2001.0     1        5     Dr.H   BT7 4MC
1     3         7      7   199.6     3        7  Dr.Kerr  BT72 4TX

Or another way is to use set_index and map :

df1['Postcode'] = df1['Practice'].map(df2.set_index('Prac No')['Postcode'])
df1

Output:

   ID  Practice  Items     Cost  Postcode
0   0         5     10  2001.00   BT7 4MC
1   1        12      2    20.98       NaN
2   2         2      4   100.80       NaN
3   3         7      7   199.60  BT72 4TX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM