如何将两个数据帧连接在一起

时间:2017-11-11 02:55:54

标签: python python-2.7 pandas dataframe jupyter-notebook

我的第一个数据框有各种列,其中一列包含ID列,而我的第二个数据帧有各种列,其中一列包含No,所以我找到了两者之间的链接。但是,如何使用数字将这些信息从数据框2中分配到数据框1中的正确做法。

任何帮助将不胜感激!!!

日期框架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

数据框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

我想在数据框1中创建一个新列'Postcode'并将邮政编码分配给正确的练习

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

IIUC,我认为你要找的是合并中的'left_on'和'right_on'参数:

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

输出:

   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

或另一种方法是使用set_indexmap

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

输出:

   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