【问题标题】:How do I merge two dataframes on multiple columns when one of the columns is an index in one dataframe当其中一列是一个数据框中的索引时,如何合并多列上的两个数据框
【发布时间】:2021-12-30 10:35:36
【问题描述】:

当合并多个列时,这会起作用:

newdf = pd.merge(df1,df2, how = 'left', left_on = ['col1','col2','col3'], right_on = ['colA', 'colB','colC'])

如果我必须使用其中一个数据帧上的索引来加入,我该怎么办,因为这需要我使用 left_index = True 以便在构建 newdf 时保留左 df 索引?

【问题讨论】:

  • 您的意思是['col1','col2','col3'] 中的一列是其中一个数据帧中的index
  • @sophcles 是的。我目前的解决方法是将索引复制为临时列并使用它进行合并,但我想知道在合并两个数据框时是否可以将索引作为列合并
  • 如果你在合并步骤中重置索引,它不会改变原来的 df1 或 df2 帧,所以像 pd.merge(df1.rest_index(), df2.reset_index(), how = 'left', left_on = ['col1','col2','col3'], right_on = ['colA', 'colB','colC']) 这样的就可以了。
  • 这行得通。非常感谢您的回复。
  • 只是想把它放在这里 newdf = pd.merge(df1,df2, how = 'left', left_on = [df1.index,'col2','col3'], right_on = [ df2.index, 'colB','colC']) 也有效

标签: python pandas dataframe merge


【解决方案1】:
newdf = pd.merge(df1,df2, how = 'left', left_on = [df1.index,'col2','col3'], right_on = [df2.index, 'colB','colC']) 

除了@StevenS 解决方案之外也可以使用。

【讨论】:

    猜你喜欢
    • 2018-02-17
    • 2021-01-11
    • 2021-03-01
    • 2017-08-02
    • 2021-11-20
    • 2015-10-28
    • 2019-10-27
    • 2012-11-25
    • 1970-01-01
    相关资源
    最近更新 更多