【问题标题】:Python Dataframes not merging on indexPython数据框未在索引上合并
【发布时间】:2018-06-10 02:38:23
【问题描述】:

我正在尝试合并 2 个数据帧,但由于某种原因它抛出了 KeyError: Player_Id

我正在尝试合并 Striker_IdPlayer_Id

这就是我的数据框的样子

合并代码:

player_runs.merge(matches_played_by_players,left_on='Striker_Id',right_on='Player_Id',how='left')

我做错了什么?

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    嗯,从您的问题来看,您似乎正在尝试合并索引,但您将它们视为列?尝试更改您的合并代码 -

    player_runs.merge(matches_played_by_players,
                      left_index=True,
                      right_index=True,
                      how='left')
    

    此外,请确保两个索引的类型相同(在这种情况下,请考虑 strint?)

    player_runs.index = player_runs.index.astype(int)
    

    还有,

    matches_played_by_players.index = matches_played_by_players.index.astype(int)      
    

    【讨论】:

    • 两个索引都是Int64,我运行了你的代码,得到一个新错误:ValueError: left_index parameter must be of type bool, not <class 'str'>
    • @JaskaranSinghPuri 你应该输入True,而不是"True" :-)
    • 成功了!谢谢,但是我们没有定义左右索引的 index_name 是什么,它是怎么知道加入它们的?
    • @JaskaranSinghPuri 指定要加入索引。这就是 pandas 执行合并所需的所有信息 :)
    【解决方案2】:

    您基本上是在合并不存在的列。这是因为reset_index 创建了一个新的数据框,而不是更改它所应用的数据框。使用 reset_index 时设置参数 inplace=True 应该可以解决此问题,或者合并每个数据帧的索引。即

    pd.merge(df1,df2,left_index=True,right_index=True,how='left')
    

    【讨论】:

    • 我只是在解释错误背后的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2019-12-09
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多