【问题标题】:Pandas not merging on different columns - Key error or NaN熊猫没有在不同的列上合并 - 键错误或 NaN
【发布时间】:2019-09-25 15:37:23
【问题描述】:

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

  • 两者都是作为数据框导入的 CSV 文件;
  • 两个列名都没有空格;
  • 两列具有相同的 d.type

我曾尝试在此处查看其他答案,将编码答案复制并粘贴到我的部分中,但仍然出现错误或 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.

【问题讨论】:

  • 您将 csv1 与 csv2 的一列(位置)合并,因此显然它没有列号来合并数据。你需要。 pd.merge(CSV1, CSV2[['Location', 'Number']], left_on='Code', right_on='Number', how='left') 你可以稍后删除 Number

标签: python pandas


【解决方案1】:

对于您的两个命令,您需要在右侧数据框中存在Number。对于第一个命令,您需要在 merge 之后删除 Number 列。对于第二个命令,您需要在右侧切片数据帧上 set_index,无需删除 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

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 2019-05-10
    • 2019-01-03
    • 2018-03-27
    • 1970-01-01
    • 2018-05-05
    • 2020-04-08
    • 2015-05-28
    • 2020-08-06
    相关资源
    最近更新 更多