python - 合并 Pandas 中的 2 个数据帧不合并第二个数据帧

标签 python pandas join dataframe merge

dataframe A 看起来像

      1st      name
0     01       AA
1     02       AB
2     03       AC
3     04       AD
4     05       AE

B 看起来像

   pred    1st     2nd
0  0.25    03       01
1  0.00    01       03
2  0.73    02       05
3  0.93    02       01
4  0.44    01       02

我希望结果看起来像

   pred    1st     2nd   1stName 2ndName
0  0.25    03       01      AC       AA
1  0.00    01       03      AA       AC
2  0.73    02       05      AB       AE
3  0.93    02       01      AB       AA
4  0.44    01       02      AA       AB

我试过了

res = pd.merge(A,B, on='1st', how='outer')

但是我得到了一个零行的数据框

如何以这种方式合并这些数据框?

编辑: 我得到的结果数据框看起来像

   pred    1st     2nd  name
0  0.25    03       01  NaN
1  0.00    01       03  NaN
2  0.73    02       05  NaN
3  0.93    02       01  NaN
4  0.44    01       02  NaN

最佳答案

你可以使用merge ,合并后,将 1st 分配给 1st & 2nd,最后删除不需要的列。

df= pd.merge(df2,df1[['name','1st']], right_on='1st',left_on='1st',how='left')
df= pd.merge(df,df1[['name','1st']], right_on='1st',left_on='2nd',how='left')
df[['1stName','2ndName']] =df[['name_x','name_y']] 
df=df[['pred','1st_x','2nd','1stName', '2ndName']]
print df

输出

   pred  1st_x  2nd 1stName 2ndName
0  0.25      3    1      AC      AA
1  0.00      1    3      AA      AC
2  0.73      2    5      AB      AE
3  0.93      2    1      AB      AA
4  0.44      1    2      AA      AB

关于python - 合并 Pandas 中的 2 个数据帧不合并第二个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423836/

相关文章:

join - 无法加入 Kubernetes 集群

python - skimage 在 LAB 色彩空间中为每个 channel 使用什么范围?

PHP + Python - 使用 PHP 将字符串传递给 Python 程序,并解析输出

python - 在 python 上的矩阵一侧创建条形

python - 如何使用Inception-v3作为卷积网络

具有两个连接的 MySQL 查询

python - 字典中一个键的多个值

Python- Pandas 按列值的升序减去列值

python-3.x - pandas 中的列串联

mysql - 您是否必须连接表 "ON"字段,或者您可以在 where 子句中将它们等同起来?