首页 > 解决方案 > 熊猫没有在不同的列上合并 - 键错误或 NaN

问题描述

我试图用我当前的数据来模仿我的问题。我正在尝试使用 pandas 合并不同列名(代码和编号)上的两个数据框,并从 df2 (位置)中只带来一列。我收到密钥错误或 NaN。

我曾尝试在这里查看其他答案,将编码答案复制并粘贴到我的部分中,但仍然会出现错误或 NaN。

df1:
[['Name', 'Income', 'Favourite superhero', 'Code', 'Colour'], 
['Joe', '80000', 'Batman', '10004', 'Red'], 
['Christine', '50000', 'Superman', '10005', 'Brown'], 
['Joey', '90000', 'Aquaman', '10002', 'Blue']

df2:
[['Number', 'Language', 'Location'], 
['10005', 'English', 'Sudbury'], 
['10002', 'French', 'Ottawa'], 
['10004', 'German', 'New York']]


what I tried:

data = pd.merge(CSV1, 
                  CSV2[['Location']],
                  left_on='Code',
                  right_on='Number',
                  how='left')

data = pd.merge(CSV1, 
                  CSV2[['Location']],
                  left_on='Code',
                  right_index=True,
                  how='left')

I am trying to have df1 with the location column from df2 for each instance where Number 
and Code are the same.

标签: pythonpandas

解决方案


对于您的两个命令都有效,您需要Number存在于右侧数据框中。对于第一个命令,您需要Numbermerge. 对于第二个命令,您需要set_index在正确的切片数据帧上,不需要 drop Number。我相应地修改了您的命令:

CSV1.merge(CSV2[['Number', 'Location']], left_on='Code', right_on='Number', how='left').drop('Number', 1)

或者

CSV1.merge(CSV2[['Number', 'Location']].set_index('Number'), left_on='Code', right_index=True, how='left')


Out[892]:
        Name Income Favourite superhero   Code Colour  Location
0        Joe  80000              Batman  10004    Red  New York
1  Christine  50000            Superman  10005  Brown   Sudbury
2       Joey  90000             Aquaman  10002   Blue    Ottawa

推荐阅读