在Python中映射数据帧

在Python中映射数据帧,python,pandas,Python,Pandas,我试图用python将一个数据帧映射到另一个数据帧。这两个表是: name age grade code Willard 20 88 2877 Al 19 92 3000 Omar 22 95 3710 Spencer 21 70 4001 Abin 18 76 2338 以及: 第一个表的“代码”列和第二个表的“秒代码”指的是同一件事,因此我想将“代码”映射到“秒编号”,如果第

我试图用python将一个数据帧映射到另一个数据帧。这两个表是:

name    age   grade   code
Willard 20     88     2877
 Al     19     92     3000
Omar    22     95     3710
Spencer 21     70     4001
Abin    18     76     2338
以及:

第一个表的“代码”列和第二个表的“秒代码”指的是同一件事,因此我想将“代码”映射到“秒编号”,如果第二个表中不存在代码,则填写相关消息

简单地说,我想创建一个最终的表,如下所示:

name    age  grade  code  sec.number
Willard 20    88    2877  10003
Al      19    92    3000  98822
Omar    22    95    3710  Not match
Spencer 21    70    4001  Not match
Abin    18    76    2338  11223
我对python没有太多经验,这就是我所尝试的:

for i in First_table['code']:
   for j in Second_table['sec.Code']:
    if i == j:
        First_table['sec_number'] = Second_table['sec.Code']
    else:
        First_table['sec_number'] = "Not match"
显然,这是行不通的。您能告诉我如何在迭代过程中为特定单元格赋值吗?当然,如果有一个更有效和“聪明”的方法来做到这一点

谢谢选项1
合并
左侧为
代码
,右侧为
秒代码

df1.merge(df2, left_on='code', right_on='sec.Code', how='left').drop(['sec.Code'], axis=1).fillna('Not match')

name       age  grade   code    sec.number
0   Willard 20  88      2877         10003
1   Al      19  92      3000         98822
2   Omar    22  95      3710     Not match
3   Spencer 21  70      4001     Not match
4   Abin    18  76      2338         11223
df1.set_index('code').join(df2.set_index('sec.Code')).reset_index().fillna('Not match')

    code    name    age grade   sec.number
0   2877    Willard 20  88           10003
1   3000    Al      19  92           98822
2   3710    Omar    22  95       Not match
3   4001    Spencer 21  70       Not match
4   2338    Abin    18  76           11223
选项2
设置索引
连接

df1.merge(df2, left_on='code', right_on='sec.Code', how='left').drop(['sec.Code'], axis=1).fillna('Not match')

name       age  grade   code    sec.number
0   Willard 20  88      2877         10003
1   Al      19  92      3000         98822
2   Omar    22  95      3710     Not match
3   Spencer 21  70      4001     Not match
4   Abin    18  76      2338         11223
df1.set_index('code').join(df2.set_index('sec.Code')).reset_index().fillna('Not match')

    code    name    age grade   sec.number
0   2877    Willard 20  88           10003
1   3000    Al      19  92           98822
2   3710    Omar    22  95       Not match
3   4001    Spencer 21  70       Not match
4   2338    Abin    18  76           11223

好啊那问题是什么?你能帮我吗?确定你粘了什么?你的哪种方法不起作用?你犯了什么错误?我是说如何在pyhon中做到这一点。谢谢,你至少需要自己尝试一下。如果你做了,展示你的方法和你的困境等等。因为你在处理数据帧,我们假设你有一些经验,很乐意帮助。如果这回答了您的问题,请查看